Coverage Report

Created: 2023-12-30 01:12

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90.1 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ                   https://dearimgui.com/faq
11
// - Getting Started       https://dearimgui.com/getting-started
12
// - Homepage              https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
// - Tests & Automation    https://github.com/ocornut/imgui_test_engine
19
20
// For first-time users having issues compiling/linking/running/loading fonts:
21
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
23
24
// Copyright (c) 2014-2023 Omar Cornut
25
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26
// See LICENSE.txt for copyright and licensing details (standard MIT License).
27
// This library is free but needs your support to sustain development and maintenance.
28
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
29
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
30
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
31
32
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
33
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
34
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
35
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
36
// to a better solution or official support for them.
37
38
/*
39
40
Index of this file:
41
42
DOCUMENTATION
43
44
- MISSION STATEMENT
45
- CONTROLS GUIDE
46
- PROGRAMMER GUIDE
47
  - READ FIRST
48
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
49
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
50
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
51
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
52
- API BREAKING CHANGES (read me when you update!)
53
- FREQUENTLY ASKED QUESTIONS (FAQ)
54
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
55
56
CODE
57
(search for "[SECTION]" in the code to find them)
58
59
// [SECTION] INCLUDES
60
// [SECTION] FORWARD DECLARATIONS
61
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
62
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
63
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
64
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
65
// [SECTION] MISC HELPERS/UTILITIES (File functions)
66
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
67
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
68
// [SECTION] ImGuiStorage
69
// [SECTION] ImGuiTextFilter
70
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
71
// [SECTION] ImGuiListClipper
72
// [SECTION] STYLING
73
// [SECTION] RENDER HELPERS
74
// [SECTION] INITIALIZATION, SHUTDOWN
75
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
76
// [SECTION] INPUTS
77
// [SECTION] ERROR CHECKING
78
// [SECTION] LAYOUT
79
// [SECTION] SCROLLING
80
// [SECTION] TOOLTIPS
81
// [SECTION] POPUPS
82
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
83
// [SECTION] DRAG AND DROP
84
// [SECTION] LOGGING/CAPTURING
85
// [SECTION] SETTINGS
86
// [SECTION] LOCALIZATION
87
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
88
// [SECTION] DOCKING
89
// [SECTION] PLATFORM DEPENDENT HELPERS
90
// [SECTION] METRICS/DEBUGGER WINDOW
91
// [SECTION] DEBUG LOG WINDOW
92
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
93
94
*/
95
96
//-----------------------------------------------------------------------------
97
// DOCUMENTATION
98
//-----------------------------------------------------------------------------
99
100
/*
101
102
 MISSION STATEMENT
103
 =================
104
105
 - Easy to use to create code-driven and data-driven tools.
106
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
107
 - Easy to hack and improve.
108
 - Minimize setup and maintenance.
109
 - Minimize state storage on user side.
110
 - Minimize state synchronization.
111
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
112
 - Efficient runtime and memory consumption.
113
114
 Designed primarily for developers and content-creators, not the typical end-user!
115
 Some of the current weaknesses (which we aim to address in the future) includes:
116
117
 - Doesn't look fancy.
118
 - Limited layout features, intricate layouts are typically crafted in code.
119
120
121
 CONTROLS GUIDE
122
 ==============
123
124
 - MOUSE CONTROLS
125
   - Mouse wheel:                   Scroll vertically.
126
   - SHIFT+Mouse wheel:             Scroll horizontally.
127
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
128
   - Click ^, Double-Click title:   Collapse window.
129
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
130
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
131
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
132
133
 - TEXT EDITOR
134
   - Hold SHIFT or Drag Mouse:      Select text.
135
   - CTRL+Left/Right:               Word jump.
136
   - CTRL+Shift+Left/Right:         Select words.
137
   - CTRL+A or Double-Click:        Select All.
138
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
139
   - CTRL+Z, CTRL+Y:                Undo, Redo.
140
   - ESCAPE:                        Revert text to its original value.
141
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
142
143
 - KEYBOARD CONTROLS
144
   - Basic:
145
     - Tab, SHIFT+Tab               Cycle through text editable fields.
146
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
147
     - CTRL+Click                   Input text into a Slider or Drag widget.
148
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
149
     - Tab, SHIFT+Tab:              Cycle through every items.
150
     - Arrow keys                   Move through items using directional navigation. Tweak value.
151
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
152
     - Enter                        Activate item (prefer text input when possible).
153
     - Space                        Activate item (prefer tweaking with arrows when possible).
154
     - Escape                       Deactivate item, leave child window, close popup.
155
     - Page Up, Page Down           Previous page, next page.
156
     - Home, End                    Scroll to top, scroll to bottom.
157
     - Alt                          Toggle between scrolling layer and menu layer.
158
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
159
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
160
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
161
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
162
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
163
164
 - GAMEPAD CONTROLS
165
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
166
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
167
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
168
   - Backend support: backend needs to:
169
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
170
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
171
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
172
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
173
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
174
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
175
176
 - REMOTE INPUTS SHARING & MOUSE EMULATION
177
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
178
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
179
     in order to share your PC mouse/keyboard.
180
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
181
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
182
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
183
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
184
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
185
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
186
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
187
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
188
189
190
 PROGRAMMER GUIDE
191
 ================
192
193
 READ FIRST
194
 ----------
195
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
196
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
197
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
198
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
199
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
200
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
201
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
202
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
203
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
204
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
205
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
206
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
207
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
208
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
209
   If you get an assert, read the messages and comments around the assert.
210
 - This codebase aims to be highly optimized:
211
   - A typical idle frame should never call malloc/free.
212
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
213
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
214
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
215
 - This codebase aims to be both highly opinionated and highly flexible:
216
   - This code works because of the things it choose to solve or not solve.
217
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
218
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
219
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
220
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
221
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
222
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
223
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
224
     (so don't use ImVector in your code or at our own risk!).
225
   - Building: We don't use nor mandate a build system for the main library.
226
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
227
     This is also because providing a build system for the main library would be of little-value.
228
     The build problems are almost never coming from the main library but from specific backends.
229
230
231
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
232
 ----------------------------------------------
233
 - Update submodule or copy/overwrite every file.
234
 - About imconfig.h:
235
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
236
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
237
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
238
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
239
240
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
241
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
242
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
243
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
244
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
245
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
246
   likely be a comment about it. Please report any issue to the GitHub page!
247
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
248
 - Try to keep your copy of Dear ImGui reasonably up to date!
249
250
251
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
252
 ---------------------------------------------------------------
253
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
254
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
255
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
256
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
257
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
258
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
259
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
260
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
261
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
262
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
263
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
264
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
265
266
267
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
268
 --------------------------------------
269
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
270
 The sub-folders in examples/ contain examples applications following this structure.
271
272
     // Application init: create a dear imgui context, setup some options, load fonts
273
     ImGui::CreateContext();
274
     ImGuiIO& io = ImGui::GetIO();
275
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
276
     // TODO: Fill optional fields of the io structure later.
277
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
278
279
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
280
     ImGui_ImplWin32_Init(hwnd);
281
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
282
283
     // Application main loop
284
     while (true)
285
     {
286
         // Feed inputs to dear imgui, start new frame
287
         ImGui_ImplDX11_NewFrame();
288
         ImGui_ImplWin32_NewFrame();
289
         ImGui::NewFrame();
290
291
         // Any application code here
292
         ImGui::Text("Hello, world!");
293
294
         // Render dear imgui into screen
295
         ImGui::Render();
296
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
297
         g_pSwapChain->Present(1, 0);
298
     }
299
300
     // Shutdown
301
     ImGui_ImplDX11_Shutdown();
302
     ImGui_ImplWin32_Shutdown();
303
     ImGui::DestroyContext();
304
305
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
306
307
     // Application init: create a dear imgui context, setup some options, load fonts
308
     ImGui::CreateContext();
309
     ImGuiIO& io = ImGui::GetIO();
310
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
311
     // TODO: Fill optional fields of the io structure later.
312
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
313
314
     // Build and load the texture atlas into a texture
315
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
316
     int width, height;
317
     unsigned char* pixels = nullptr;
318
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
319
320
     // At this point you've got the texture data and you need to upload that to your graphic system:
321
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
322
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
323
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
324
     io.Fonts->SetTexID((void*)texture);
325
326
     // Application main loop
327
     while (true)
328
     {
329
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
330
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
331
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
332
        io.DisplaySize.x = 1920.0f;             // set the current display width
333
        io.DisplaySize.y = 1280.0f;             // set the current display height here
334
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
335
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
336
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
337
338
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
339
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
340
        ImGui::NewFrame();
341
342
        // Most of your application code here
343
        ImGui::Text("Hello, world!");
344
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
345
        MyGameRender(); // may use any Dear ImGui functions as well!
346
347
        // Render dear imgui, swap buffers
348
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
349
        ImGui::EndFrame();
350
        ImGui::Render();
351
        ImDrawData* draw_data = ImGui::GetDrawData();
352
        MyImGuiRenderFunction(draw_data);
353
        SwapBuffers();
354
     }
355
356
     // Shutdown
357
     ImGui::DestroyContext();
358
359
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
360
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
361
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
362
363
364
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
365
 ---------------------------------------------
366
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
367
368
    void MyImGuiRenderFunction(ImDrawData* draw_data)
369
    {
370
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
371
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
372
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
373
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
374
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
375
       ImVec2 clip_off = draw_data->DisplayPos;
376
       for (int n = 0; n < draw_data->CmdListsCount; n++)
377
       {
378
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
379
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
380
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
381
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
382
          {
383
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
384
             if (pcmd->UserCallback)
385
             {
386
                 pcmd->UserCallback(cmd_list, pcmd);
387
             }
388
             else
389
             {
390
                 // Project scissor/clipping rectangles into framebuffer space
391
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
392
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
393
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
394
                     continue;
395
396
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
397
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
398
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
399
                 // - Clipping coordinates are provided in imgui coordinates space:
400
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
401
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
402
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
403
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
404
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
405
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
406
407
                 // The texture for the draw call is specified by pcmd->GetTexID().
408
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
409
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
410
411
                 // Render 'pcmd->ElemCount/3' indexed triangles.
412
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
413
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
414
             }
415
          }
416
       }
417
    }
418
419
420
 API BREAKING CHANGES
421
 ====================
422
423
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
424
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
425
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
426
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
427
428
(Docking/Viewport Branch)
429
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
430
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
431
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
432
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
433
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
434
435
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
436
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
437
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
438
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
439
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
440
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
441
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
442
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
443
                           - old: BeginChild("Name", size, true)
444
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
445
                           - old: BeginChild("Name", size, false)
446
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
447
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
448
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
449
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
450
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
451
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
452
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
453
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
454
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
455
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
456
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
457
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
458
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
459
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
460
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
461
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
462
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
463
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
464
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
465
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
466
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
467
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
468
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
469
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
470
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
471
                           - ListBoxFooter()  -> use EndListBox()
472
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
473
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
474
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
475
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
476
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
477
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
478
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
479
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
480
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
481
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
482
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
483
                         it has been frequently requested by people to use our own. We had an opt-in define which was
484
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
485
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
486
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
487
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
488
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
489
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
490
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
491
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
492
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
493
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
494
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
495
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
496
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
497
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
498
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
499
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
500
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
501
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
502
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
503
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
504
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
505
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
506
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
507
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
508
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
509
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
510
                         - previously this would make the window content size ~200x200:
511
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
512
                         - instead, please submit an item:
513
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
514
                         - alternative:
515
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
516
                         - content size is now only extended when submitting an item!
517
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
518
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
519
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
520
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
521
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
522
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
523
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
524
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
525
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
526
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
527
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
528
                        - Official backends from 1.87+                  -> no issue.
529
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
530
                        - Custom backends not writing to io.NavInputs[] -> no issue.
531
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
532
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
533
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
534
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
535
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
536
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
537
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
538
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
539
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
540
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
541
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
542
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
543
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
544
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
545
                       read https://github.com/ocornut/imgui/issues/4921 for details.
546
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
547
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
548
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
549
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
550
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
551
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
552
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
553
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
554
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
555
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
556
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
557
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
558
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
559
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
560
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
561
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
562
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
563
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
564
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
565
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
566
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
567
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
568
                        - if you are using official backends from the source tree: you have nothing to do.
569
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
570
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
571
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
572
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
573
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
574
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
575
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
576
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
577
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
578
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
579
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
580
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
581
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
582
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
583
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
584
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
585
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
586
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
587
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
588
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
589
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
590
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
591
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
592
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
593
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
594
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
595
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
596
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
597
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
598
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
599
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
600
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
601
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
602
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
603
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
604
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
605
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
606
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
607
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
608
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
609
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
610
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
611
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
612
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
613
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
614
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
615
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
616
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
617
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
618
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
619
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
620
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
621
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
622
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
623
                       - if you omitted the 'power' parameter (likely!), you are not affected.
624
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
625
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
626
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
627
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
628
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
629
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
630
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
631
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
632
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
633
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
634
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
635
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
636
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
637
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
638
                       - ShowTestWindow()                    -> use ShowDemoWindow()
639
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
640
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
641
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
642
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
643
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
644
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
645
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
646
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
647
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
648
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
649
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
650
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
651
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
652
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
653
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
654
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
655
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
656
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
657
                       - ImFont::Glyph                       -> use ImFontGlyph
658
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
659
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
660
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
661
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
662
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
663
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
664
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
665
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
666
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
667
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
668
                       Please reach out if you are affected.
669
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
670
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
671
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
672
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
673
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
674
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
675
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
676
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
677
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
678
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
679
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
680
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
681
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
682
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
683
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
684
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
685
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
686
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
687
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
688
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
689
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
690
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
691
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
692
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
693
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
694
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
695
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
696
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
697
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
698
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
699
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
700
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
701
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
702
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
703
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
704
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
705
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
706
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
707
                       consistent with other functions. Kept redirection functions (will obsolete).
708
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
709
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
710
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
711
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
712
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
713
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
714
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
715
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
716
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
717
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
718
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
719
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
720
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
721
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
722
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
723
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
724
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
725
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
726
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
727
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
728
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
729
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
730
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
731
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
732
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
733
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
734
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
735
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
736
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
737
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
738
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
739
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
740
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
741
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
742
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
743
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
744
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
745
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
746
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
747
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
748
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
749
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
750
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
751
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
752
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
753
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
754
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
755
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
756
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
757
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
758
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
759
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
760
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
761
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
762
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
763
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
764
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
765
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
766
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
767
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
768
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
769
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
770
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
771
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
772
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
773
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
774
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
775
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
776
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
777
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
778
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
779
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
780
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
781
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
782
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
783
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
784
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
785
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
786
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
787
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
788
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
789
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
790
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
791
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
792
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
793
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
794
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
795
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
796
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
797
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
798
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
799
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
800
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
801
                     - the signature of the io.RenderDrawListsFn handler has changed!
802
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
803
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
804
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
805
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
806
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
807
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
808
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
809
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
810
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
811
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
812
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
813
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
814
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
815
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
816
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
817
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
818
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
819
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
820
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
821
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
822
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
823
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
824
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
825
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
826
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
827
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
828
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
829
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
830
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
831
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
832
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
833
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
834
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
835
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
836
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
837
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
838
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
839
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
840
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
841
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
842
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
843
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
844
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
845
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
846
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
847
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
848
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
849
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
850
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
851
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
852
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
853
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
854
855
856
 FREQUENTLY ASKED QUESTIONS (FAQ)
857
 ================================
858
859
 Read all answers online:
860
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
861
 Read all answers locally (with a text editor or ideally a Markdown viewer):
862
   docs/FAQ.md
863
 Some answers are copied down here to facilitate searching in code.
864
865
 Q&A: Basics
866
 ===========
867
868
 Q: Where is the documentation?
869
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
870
    - Run the examples/ applications and explore them.
871
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
872
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
873
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
874
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
875
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
876
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
877
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
878
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
879
    - Your programming IDE is your friend, find the type or function declaration to find comments
880
      associated with it.
881
882
 Q: What is this library called?
883
 Q: Which version should I get?
884
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
885
 >> See https://www.dearimgui.com/faq for details.
886
887
 Q&A: Integration
888
 ================
889
890
 Q: How to get started?
891
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
892
893
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
894
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
895
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
896
897
 Q. How can I enable keyboard or gamepad controls?
898
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
899
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
900
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
901
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
902
 >> See https://www.dearimgui.com/faq
903
904
 Q&A: Usage
905
 ----------
906
907
 Q: About the ID Stack system..
908
   - Why is my widget not reacting when I click on it?
909
   - How can I have widgets with an empty label?
910
   - How can I have multiple widgets with the same label?
911
   - How can I have multiple windows with the same label?
912
 Q: How can I display an image? What is ImTextureID, how does it work?
913
 Q: How can I use my own math types instead of ImVec2?
914
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
915
 Q: How can I display custom shapes? (using low-level ImDrawList API)
916
 >> See https://www.dearimgui.com/faq
917
918
 Q&A: Fonts, Text
919
 ================
920
921
 Q: How should I handle DPI in my application?
922
 Q: How can I load a different font than the default?
923
 Q: How can I easily use icons in my application?
924
 Q: How can I load multiple fonts?
925
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
926
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
927
928
 Q&A: Concerns
929
 =============
930
931
 Q: Who uses Dear ImGui?
932
 Q: Can you create elaborate/serious tools with Dear ImGui?
933
 Q: Can you reskin the look of Dear ImGui?
934
 Q: Why using C++ (as opposed to C)?
935
 >> See https://www.dearimgui.com/faq
936
937
 Q&A: Community
938
 ==============
939
940
 Q: How can I help?
941
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
942
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
943
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
944
      Also see https://github.com/ocornut/imgui/wiki/Sponsors
945
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
946
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
947
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
948
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
949
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
950
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
951
952
*/
953
954
//-------------------------------------------------------------------------
955
// [SECTION] INCLUDES
956
//-------------------------------------------------------------------------
957
958
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
959
#define _CRT_SECURE_NO_WARNINGS
960
#endif
961
962
#ifndef IMGUI_DEFINE_MATH_OPERATORS
963
#define IMGUI_DEFINE_MATH_OPERATORS
964
#endif
965
966
#include "imgui.h"
967
#ifndef IMGUI_DISABLE
968
#include "imgui_internal.h"
969
970
// System includes
971
#include <stdio.h>      // vsnprintf, sscanf, printf
972
#include <stdint.h>     // intptr_t
973
974
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
975
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
976
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
977
#endif
978
979
// [Windows] OS specific includes (optional)
980
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
981
#define IMGUI_DISABLE_WIN32_FUNCTIONS
982
#endif
983
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
984
#ifndef WIN32_LEAN_AND_MEAN
985
#define WIN32_LEAN_AND_MEAN
986
#endif
987
#ifndef NOMINMAX
988
#define NOMINMAX
989
#endif
990
#ifndef __MINGW32__
991
#include <Windows.h>        // _wfopen, OpenClipboard
992
#else
993
#include <windows.h>
994
#endif
995
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
996
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
997
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
998
#endif
999
#endif
1000
1001
// [Apple] OS specific includes
1002
#if defined(__APPLE__)
1003
#include <TargetConditionals.h>
1004
#endif
1005
1006
// Visual Studio warnings
1007
#ifdef _MSC_VER
1008
#pragma warning (disable: 4127)             // condition expression is constant
1009
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1010
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1011
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1012
#endif
1013
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1014
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1015
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1016
#endif
1017
1018
// Clang/GCC warnings with -Weverything
1019
#if defined(__clang__)
1020
#if __has_warning("-Wunknown-warning-option")
1021
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1022
#endif
1023
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1024
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1025
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1026
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1027
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1028
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1029
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1030
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1031
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1032
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1033
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1034
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1035
#elif defined(__GNUC__)
1036
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1037
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1038
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1039
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1040
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1041
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1042
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1043
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1044
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1045
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1046
#endif
1047
1048
// Debug options
1049
156k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1050
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1051
1052
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1053
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1054
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1055
1056
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1057
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1058
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1059
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1060
1061
// Tooltip offset
1062
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1063
1064
// Docking
1065
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1066
1067
//-------------------------------------------------------------------------
1068
// [SECTION] FORWARD DECLARATIONS
1069
//-------------------------------------------------------------------------
1070
1071
static void             SetCurrentWindow(ImGuiWindow* window);
1072
static void             FindHoveredWindow();
1073
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1074
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1075
1076
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1077
1078
// Settings
1079
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1080
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1081
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1082
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1083
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1084
1085
// Platform Dependents default implementation for IO functions
1086
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1087
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1088
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1089
1090
namespace ImGui
1091
{
1092
// Navigation
1093
static void             NavUpdate();
1094
static void             NavUpdateWindowing();
1095
static void             NavUpdateWindowingOverlay();
1096
static void             NavUpdateCancelRequest();
1097
static void             NavUpdateCreateMoveRequest();
1098
static void             NavUpdateCreateTabbingRequest();
1099
static float            NavUpdatePageUpPageDown();
1100
static inline void      NavUpdateAnyRequestFlag();
1101
static void             NavUpdateCreateWrappingRequest();
1102
static void             NavEndFrame();
1103
static bool             NavScoreItem(ImGuiNavItemData* result);
1104
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1105
static void             NavProcessItem();
1106
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1107
static ImVec2           NavCalcPreferredRefPos();
1108
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1109
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1110
static void             NavRestoreLayer(ImGuiNavLayer layer);
1111
static int              FindWindowFocusIndex(ImGuiWindow* window);
1112
1113
// Error Checking and Debug Tools
1114
static void             ErrorCheckNewFrameSanityChecks();
1115
static void             ErrorCheckEndFrameSanityChecks();
1116
static void             UpdateDebugToolItemPicker();
1117
static void             UpdateDebugToolStackQueries();
1118
static void             UpdateDebugToolFlashStyleColor();
1119
1120
// Inputs
1121
static void             UpdateKeyboardInputs();
1122
static void             UpdateMouseInputs();
1123
static void             UpdateMouseWheel();
1124
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1125
1126
// Misc
1127
static void             UpdateSettings();
1128
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1129
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1130
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1131
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1132
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1133
static void             RenderDimmedBackgrounds();
1134
1135
// Viewports
1136
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1137
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1138
static void             DestroyViewport(ImGuiViewportP* viewport);
1139
static void             UpdateViewportsNewFrame();
1140
static void             UpdateViewportsEndFrame();
1141
static void             WindowSelectViewport(ImGuiWindow* window);
1142
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1143
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1144
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1145
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1146
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1147
static int              FindPlatformMonitorForRect(const ImRect& r);
1148
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1149
1150
}
1151
1152
//-----------------------------------------------------------------------------
1153
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1154
//-----------------------------------------------------------------------------
1155
1156
// DLL users:
1157
// - Heaps and globals are not shared across DLL boundaries!
1158
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1159
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1160
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1161
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1162
1163
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1164
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1165
//   Change to a different context by calling ImGui::SetCurrentContext().
1166
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1167
//   If you want thread-safety to allow N threads to access N different contexts:
1168
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1169
//         struct ImGuiContext;
1170
//         extern thread_local ImGuiContext* MyImGuiTLS;
1171
//         #define GImGui MyImGuiTLS
1172
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1173
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1174
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1175
// - DLL users: read comments above.
1176
#ifndef GImGui
1177
ImGuiContext*   GImGui = NULL;
1178
#endif
1179
1180
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1181
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1182
// - DLL users: read comments above.
1183
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1184
1.24k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1185
1.19k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1186
#else
1187
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1188
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1189
#endif
1190
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1191
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1192
static void*                GImAllocatorUserData = NULL;
1193
1194
//-----------------------------------------------------------------------------
1195
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1196
//-----------------------------------------------------------------------------
1197
1198
ImGuiStyle::ImGuiStyle()
1199
1
{
1200
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1201
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1202
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1203
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1204
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1205
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1206
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1207
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1208
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1209
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1210
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1211
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1212
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1213
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1214
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1215
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1216
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1217
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. CellPadding.y may be altered between different rows.
1218
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1219
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1220
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1221
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1222
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1223
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1224
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1225
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1226
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1227
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1228
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1229
1
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1230
1
    TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1231
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1232
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1233
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1234
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1235
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1236
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1237
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1238
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1239
1
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1240
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1241
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1242
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1243
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1244
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1245
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1246
1247
    // Behaviors
1248
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1249
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1250
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1251
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1252
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1253
1254
    // Default theme
1255
1
    ImGui::StyleColorsDark(this);
1256
1
}
1257
1258
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1259
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1260
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1261
0
{
1262
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1263
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1264
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1265
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1266
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1267
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1268
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1269
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1270
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1271
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1272
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1273
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1274
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1275
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1276
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1277
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1278
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1279
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1280
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1281
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1282
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1283
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1284
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1285
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1286
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1287
0
}
1288
1289
ImGuiIO::ImGuiIO()
1290
1
{
1291
    // Most fields are initialized with zero
1292
1
    memset(this, 0, sizeof(*this));
1293
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1294
1295
    // Settings
1296
1
    ConfigFlags = ImGuiConfigFlags_None;
1297
1
    BackendFlags = ImGuiBackendFlags_None;
1298
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1299
1
    DeltaTime = 1.0f / 60.0f;
1300
1
    IniSavingRate = 5.0f;
1301
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1302
1
    LogFilename = "imgui_log.txt";
1303
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1304
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1305
        KeyMap[i] = -1;
1306
#endif
1307
1
    UserData = NULL;
1308
1309
1
    Fonts = NULL;
1310
1
    FontGlobalScale = 1.0f;
1311
1
    FontDefault = NULL;
1312
1
    FontAllowUserScaling = false;
1313
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1314
1315
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1316
1
    ConfigDockingNoSplit = false;
1317
1
    ConfigDockingWithShift = false;
1318
1
    ConfigDockingAlwaysTabBar = false;
1319
1
    ConfigDockingTransparentPayload = false;
1320
1321
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1322
1
    ConfigViewportsNoAutoMerge = false;
1323
1
    ConfigViewportsNoTaskBarIcon = false;
1324
1
    ConfigViewportsNoDecoration = true;
1325
1
    ConfigViewportsNoDefaultParent = false;
1326
1327
    // Miscellaneous options
1328
1
    MouseDrawCursor = false;
1329
#ifdef __APPLE__
1330
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1331
#else
1332
1
    ConfigMacOSXBehaviors = false;
1333
1
#endif
1334
1
    ConfigInputTrickleEventQueue = true;
1335
1
    ConfigInputTextCursorBlink = true;
1336
1
    ConfigInputTextEnterKeepActive = false;
1337
1
    ConfigDragClickToInputText = false;
1338
1
    ConfigWindowsResizeFromEdges = true;
1339
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1340
1
    ConfigMemoryCompactTimer = 60.0f;
1341
1
    ConfigDebugBeginReturnValueOnce = false;
1342
1
    ConfigDebugBeginReturnValueLoop = false;
1343
1344
    // Inputs Behaviors
1345
1
    MouseDoubleClickTime = 0.30f;
1346
1
    MouseDoubleClickMaxDist = 6.0f;
1347
1
    MouseDragThreshold = 6.0f;
1348
1
    KeyRepeatDelay = 0.275f;
1349
1
    KeyRepeatRate = 0.050f;
1350
1351
    // Platform Functions
1352
    // Note: Initialize() will setup default clipboard/ime handlers.
1353
1
    BackendPlatformName = BackendRendererName = NULL;
1354
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1355
1
    PlatformLocaleDecimalPoint = '.';
1356
1357
    // Input (NB: we already have memset zero the entire structure!)
1358
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1359
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1360
1
    MouseSource = ImGuiMouseSource_Mouse;
1361
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1362
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1363
1
    AppAcceptingEvents = true;
1364
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1365
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1366
1
}
1367
1368
// Pass in translated ASCII characters for text input.
1369
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1370
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1371
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1372
void ImGuiIO::AddInputCharacter(unsigned int c)
1373
6.61k
{
1374
6.61k
    IM_ASSERT(Ctx != NULL);
1375
6.61k
    ImGuiContext& g = *Ctx;
1376
6.61k
    if (c == 0 || !AppAcceptingEvents)
1377
392
        return;
1378
1379
6.22k
    ImGuiInputEvent e;
1380
6.22k
    e.Type = ImGuiInputEventType_Text;
1381
6.22k
    e.Source = ImGuiInputSource_Keyboard;
1382
6.22k
    e.EventId = g.InputEventsNextEventId++;
1383
6.22k
    e.Text.Char = c;
1384
6.22k
    g.InputEventsQueue.push_back(e);
1385
6.22k
}
1386
1387
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1388
// we should save the high surrogate.
1389
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1390
6.07k
{
1391
6.07k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1392
208
        return;
1393
1394
5.86k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1395
705
    {
1396
705
        if (InputQueueSurrogate != 0)
1397
450
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1398
705
        InputQueueSurrogate = c;
1399
705
        return;
1400
705
    }
1401
1402
5.16k
    ImWchar cp = c;
1403
5.16k
    if (InputQueueSurrogate != 0)
1404
236
    {
1405
236
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1406
196
        {
1407
196
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1408
196
        }
1409
40
        else
1410
40
        {
1411
40
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1412
40
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1413
#else
1414
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1415
#endif
1416
40
        }
1417
1418
236
        InputQueueSurrogate = 0;
1419
236
    }
1420
5.16k
    AddInputCharacter((unsigned)cp);
1421
5.16k
}
1422
1423
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1424
52
{
1425
52
    if (!AppAcceptingEvents)
1426
0
        return;
1427
52
    while (*utf8_chars != 0)
1428
0
    {
1429
0
        unsigned int c = 0;
1430
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1431
0
        AddInputCharacter(c);
1432
0
    }
1433
52
}
1434
1435
// Clear all incoming events.
1436
void ImGuiIO::ClearEventsQueue()
1437
0
{
1438
0
    IM_ASSERT(Ctx != NULL);
1439
0
    ImGuiContext& g = *Ctx;
1440
0
    g.InputEventsQueue.clear();
1441
0
}
1442
1443
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1444
void ImGuiIO::ClearInputKeys()
1445
9.46k
{
1446
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1447
    memset(KeysDown, 0, sizeof(KeysDown));
1448
#endif
1449
1.46M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1450
1.45M
    {
1451
1.45M
        KeysData[n].Down             = false;
1452
1.45M
        KeysData[n].DownDuration     = -1.0f;
1453
1.45M
        KeysData[n].DownDurationPrev = -1.0f;
1454
1.45M
    }
1455
9.46k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1456
9.46k
    KeyMods = ImGuiMod_None;
1457
9.46k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1458
56.7k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1459
47.3k
    {
1460
47.3k
        MouseDown[n] = false;
1461
47.3k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1462
47.3k
    }
1463
9.46k
    MouseWheel = MouseWheelH = 0.0f;
1464
9.46k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1465
9.46k
}
1466
1467
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1468
// Current frame character buffer is now also cleared by ClearInputKeys().
1469
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1470
void ImGuiIO::ClearInputCharacters()
1471
{
1472
    InputQueueCharacters.resize(0);
1473
}
1474
#endif
1475
1476
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1477
14.7k
{
1478
14.7k
    ImGuiContext& g = *ctx;
1479
21.8k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1480
11.6k
    {
1481
11.6k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1482
11.6k
        if (e->Type != type)
1483
3.71k
            continue;
1484
7.93k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1485
1.24k
            continue;
1486
6.69k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1487
2.14k
            continue;
1488
4.54k
        return e;
1489
6.69k
    }
1490
10.1k
    return NULL;
1491
14.7k
}
1492
1493
// Queue a new key down/up event.
1494
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1495
// - bool down:          Is the key down? use false to signify a key release.
1496
// - float analog_value: 0.0f..1.0f
1497
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1498
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1499
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1500
5.17k
{
1501
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1502
5.17k
    IM_ASSERT(Ctx != NULL);
1503
5.17k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1504
0
        return;
1505
5.17k
    ImGuiContext& g = *Ctx;
1506
5.17k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1507
5.17k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1508
5.17k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1509
1510
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1511
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1512
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1513
    if (BackendUsingLegacyKeyArrays == -1)
1514
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1515
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1516
    BackendUsingLegacyKeyArrays = 0;
1517
#endif
1518
5.17k
    if (ImGui::IsGamepadKey(key))
1519
14
        BackendUsingLegacyNavInputArray = false;
1520
1521
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1522
5.17k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1523
5.17k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1524
5.17k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1525
5.17k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1526
5.17k
    if (latest_key_down == down && latest_key_analog == analog_value)
1527
1.42k
        return;
1528
1529
    // Add event
1530
3.75k
    ImGuiInputEvent e;
1531
3.75k
    e.Type = ImGuiInputEventType_Key;
1532
3.75k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1533
3.75k
    e.EventId = g.InputEventsNextEventId++;
1534
3.75k
    e.Key.Key = key;
1535
3.75k
    e.Key.Down = down;
1536
3.75k
    e.Key.AnalogValue = analog_value;
1537
3.75k
    g.InputEventsQueue.push_back(e);
1538
3.75k
}
1539
1540
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1541
4.75k
{
1542
4.75k
    if (!AppAcceptingEvents)
1543
0
        return;
1544
4.75k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1545
4.75k
}
1546
1547
// [Optional] Call after AddKeyEvent().
1548
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1549
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1550
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1551
0
{
1552
0
    if (key == ImGuiKey_None)
1553
0
        return;
1554
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1555
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1556
0
    IM_UNUSED(native_keycode);  // Yet unused
1557
0
    IM_UNUSED(native_scancode); // Yet unused
1558
1559
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1560
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1561
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1562
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1563
        return;
1564
    KeyMap[legacy_key] = key;
1565
    KeyMap[key] = legacy_key;
1566
#else
1567
0
    IM_UNUSED(key);
1568
0
    IM_UNUSED(native_legacy_index);
1569
0
#endif
1570
0
}
1571
1572
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1573
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1574
0
{
1575
0
    AppAcceptingEvents = accepting_events;
1576
0
}
1577
1578
// Queue a mouse move event
1579
void ImGuiIO::AddMousePosEvent(float x, float y)
1580
3.33k
{
1581
3.33k
    IM_ASSERT(Ctx != NULL);
1582
3.33k
    ImGuiContext& g = *Ctx;
1583
3.33k
    if (!AppAcceptingEvents)
1584
0
        return;
1585
1586
    // Apply same flooring as UpdateMouseInputs()
1587
3.33k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1588
1589
    // Filter duplicate
1590
3.33k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1591
3.33k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1592
3.33k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1593
673
        return;
1594
1595
2.66k
    ImGuiInputEvent e;
1596
2.66k
    e.Type = ImGuiInputEventType_MousePos;
1597
2.66k
    e.Source = ImGuiInputSource_Mouse;
1598
2.66k
    e.EventId = g.InputEventsNextEventId++;
1599
2.66k
    e.MousePos.PosX = pos.x;
1600
2.66k
    e.MousePos.PosY = pos.y;
1601
2.66k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1602
2.66k
    g.InputEventsQueue.push_back(e);
1603
2.66k
}
1604
1605
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1606
5.47k
{
1607
5.47k
    IM_ASSERT(Ctx != NULL);
1608
5.47k
    ImGuiContext& g = *Ctx;
1609
5.47k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1610
5.47k
    if (!AppAcceptingEvents)
1611
0
        return;
1612
1613
    // Filter duplicate
1614
5.47k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1615
5.47k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1616
5.47k
    if (latest_button_down == down)
1617
1.78k
        return;
1618
1619
3.68k
    ImGuiInputEvent e;
1620
3.68k
    e.Type = ImGuiInputEventType_MouseButton;
1621
3.68k
    e.Source = ImGuiInputSource_Mouse;
1622
3.68k
    e.EventId = g.InputEventsNextEventId++;
1623
3.68k
    e.MouseButton.Button = mouse_button;
1624
3.68k
    e.MouseButton.Down = down;
1625
3.68k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1626
3.68k
    g.InputEventsQueue.push_back(e);
1627
3.68k
}
1628
1629
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1630
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1631
854
{
1632
854
    IM_ASSERT(Ctx != NULL);
1633
854
    ImGuiContext& g = *Ctx;
1634
1635
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1636
854
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1637
20
        return;
1638
1639
834
    ImGuiInputEvent e;
1640
834
    e.Type = ImGuiInputEventType_MouseWheel;
1641
834
    e.Source = ImGuiInputSource_Mouse;
1642
834
    e.EventId = g.InputEventsNextEventId++;
1643
834
    e.MouseWheel.WheelX = wheel_x;
1644
834
    e.MouseWheel.WheelY = wheel_y;
1645
834
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1646
834
    g.InputEventsQueue.push_back(e);
1647
834
}
1648
1649
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1650
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1651
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1652
0
{
1653
0
    IM_ASSERT(Ctx != NULL);
1654
0
    ImGuiContext& g = *Ctx;
1655
0
    g.InputEventsNextMouseSource = source;
1656
0
}
1657
1658
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1659
0
{
1660
0
    IM_ASSERT(Ctx != NULL);
1661
0
    ImGuiContext& g = *Ctx;
1662
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1663
0
    if (!AppAcceptingEvents)
1664
0
        return;
1665
1666
    // Filter duplicate
1667
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1668
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1669
0
    if (latest_viewport_id == viewport_id)
1670
0
        return;
1671
1672
0
    ImGuiInputEvent e;
1673
0
    e.Type = ImGuiInputEventType_MouseViewport;
1674
0
    e.Source = ImGuiInputSource_Mouse;
1675
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1676
0
    g.InputEventsQueue.push_back(e);
1677
0
}
1678
1679
void ImGuiIO::AddFocusEvent(bool focused)
1680
741
{
1681
741
    IM_ASSERT(Ctx != NULL);
1682
741
    ImGuiContext& g = *Ctx;
1683
1684
    // Filter duplicate
1685
741
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1686
741
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1687
741
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1688
325
        return;
1689
1690
416
    ImGuiInputEvent e;
1691
416
    e.Type = ImGuiInputEventType_Focus;
1692
416
    e.EventId = g.InputEventsNextEventId++;
1693
416
    e.AppFocused.Focused = focused;
1694
416
    g.InputEventsQueue.push_back(e);
1695
416
}
1696
1697
//-----------------------------------------------------------------------------
1698
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1699
//-----------------------------------------------------------------------------
1700
1701
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1702
0
{
1703
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1704
0
    ImVec2 p_last = p1;
1705
0
    ImVec2 p_closest;
1706
0
    float p_closest_dist2 = FLT_MAX;
1707
0
    float t_step = 1.0f / (float)num_segments;
1708
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1709
0
    {
1710
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1711
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1712
0
        float dist2 = ImLengthSqr(p - p_line);
1713
0
        if (dist2 < p_closest_dist2)
1714
0
        {
1715
0
            p_closest = p_line;
1716
0
            p_closest_dist2 = dist2;
1717
0
        }
1718
0
        p_last = p_current;
1719
0
    }
1720
0
    return p_closest;
1721
0
}
1722
1723
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1724
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1725
0
{
1726
0
    float dx = x4 - x1;
1727
0
    float dy = y4 - y1;
1728
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1729
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1730
0
    d2 = (d2 >= 0) ? d2 : -d2;
1731
0
    d3 = (d3 >= 0) ? d3 : -d3;
1732
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1733
0
    {
1734
0
        ImVec2 p_current(x4, y4);
1735
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1736
0
        float dist2 = ImLengthSqr(p - p_line);
1737
0
        if (dist2 < p_closest_dist2)
1738
0
        {
1739
0
            p_closest = p_line;
1740
0
            p_closest_dist2 = dist2;
1741
0
        }
1742
0
        p_last = p_current;
1743
0
    }
1744
0
    else if (level < 10)
1745
0
    {
1746
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1747
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1748
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1749
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1750
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1751
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1752
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1753
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1754
0
    }
1755
0
}
1756
1757
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1758
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1759
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1760
0
{
1761
0
    IM_ASSERT(tess_tol > 0.0f);
1762
0
    ImVec2 p_last = p1;
1763
0
    ImVec2 p_closest;
1764
0
    float p_closest_dist2 = FLT_MAX;
1765
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1766
0
    return p_closest;
1767
0
}
1768
1769
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1770
0
{
1771
0
    ImVec2 ap = p - a;
1772
0
    ImVec2 ab_dir = b - a;
1773
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1774
0
    if (dot < 0.0f)
1775
0
        return a;
1776
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1777
0
    if (dot > ab_len_sqr)
1778
0
        return b;
1779
0
    return a + ab_dir * dot / ab_len_sqr;
1780
0
}
1781
1782
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1783
0
{
1784
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1785
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1786
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1787
0
    return ((b1 == b2) && (b2 == b3));
1788
0
}
1789
1790
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1791
0
{
1792
0
    ImVec2 v0 = b - a;
1793
0
    ImVec2 v1 = c - a;
1794
0
    ImVec2 v2 = p - a;
1795
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1796
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1797
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1798
0
    out_u = 1.0f - out_v - out_w;
1799
0
}
1800
1801
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1802
0
{
1803
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1804
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1805
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1806
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1807
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1808
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1809
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1810
0
    if (m == dist2_ab)
1811
0
        return proj_ab;
1812
0
    if (m == dist2_bc)
1813
0
        return proj_bc;
1814
0
    return proj_ca;
1815
0
}
1816
1817
//-----------------------------------------------------------------------------
1818
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1819
//-----------------------------------------------------------------------------
1820
1821
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1822
int ImStricmp(const char* str1, const char* str2)
1823
0
{
1824
0
    int d;
1825
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1826
0
    return d;
1827
0
}
1828
1829
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1830
0
{
1831
0
    int d = 0;
1832
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1833
0
    return d;
1834
0
}
1835
1836
void ImStrncpy(char* dst, const char* src, size_t count)
1837
425
{
1838
425
    if (count < 1)
1839
0
        return;
1840
425
    if (count > 1)
1841
425
        strncpy(dst, src, count - 1);
1842
425
    dst[count - 1] = 0;
1843
425
}
1844
1845
char* ImStrdup(const char* str)
1846
3
{
1847
3
    size_t len = strlen(str);
1848
3
    void* buf = IM_ALLOC(len + 1);
1849
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1850
3
}
1851
1852
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1853
0
{
1854
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1855
0
    size_t src_size = strlen(src) + 1;
1856
0
    if (dst_buf_size < src_size)
1857
0
    {
1858
0
        IM_FREE(dst);
1859
0
        dst = (char*)IM_ALLOC(src_size);
1860
0
        if (p_dst_size)
1861
0
            *p_dst_size = src_size;
1862
0
    }
1863
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1864
0
}
1865
1866
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1867
0
{
1868
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1869
0
    return p;
1870
0
}
1871
1872
int ImStrlenW(const ImWchar* str)
1873
0
{
1874
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1875
0
    int n = 0;
1876
0
    while (*str++) n++;
1877
0
    return n;
1878
0
}
1879
1880
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1881
const char* ImStreolRange(const char* str, const char* str_end)
1882
0
{
1883
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1884
0
    return p ? p : str_end;
1885
0
}
1886
1887
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1888
0
{
1889
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1890
0
        buf_mid_line--;
1891
0
    return buf_mid_line;
1892
0
}
1893
1894
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1895
0
{
1896
0
    if (!needle_end)
1897
0
        needle_end = needle + strlen(needle);
1898
1899
0
    const char un0 = (char)ImToUpper(*needle);
1900
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1901
0
    {
1902
0
        if (ImToUpper(*haystack) == un0)
1903
0
        {
1904
0
            const char* b = needle + 1;
1905
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1906
0
                if (ImToUpper(*a) != ImToUpper(*b))
1907
0
                    break;
1908
0
            if (b == needle_end)
1909
0
                return haystack;
1910
0
        }
1911
0
        haystack++;
1912
0
    }
1913
0
    return NULL;
1914
0
}
1915
1916
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1917
void ImStrTrimBlanks(char* buf)
1918
0
{
1919
0
    char* p = buf;
1920
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1921
0
        p++;
1922
0
    char* p_start = p;
1923
0
    while (*p != 0)                         // Find end of string
1924
0
        p++;
1925
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1926
0
        p--;
1927
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1928
0
        memmove(buf, p_start, p - p_start);
1929
0
    buf[p - p_start] = 0;                   // Zero terminate
1930
0
}
1931
1932
const char* ImStrSkipBlank(const char* str)
1933
0
{
1934
0
    while (str[0] == ' ' || str[0] == '\t')
1935
0
        str++;
1936
0
    return str;
1937
0
}
1938
1939
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1940
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1941
// B) When buf==NULL vsnprintf() will return the output size.
1942
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1943
1944
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1945
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1946
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1947
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1948
#ifdef IMGUI_USE_STB_SPRINTF
1949
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1950
#define STB_SPRINTF_IMPLEMENTATION
1951
#endif
1952
#ifdef IMGUI_STB_SPRINTF_FILENAME
1953
#include IMGUI_STB_SPRINTF_FILENAME
1954
#else
1955
#include "stb_sprintf.h"
1956
#endif
1957
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1958
1959
#if defined(_MSC_VER) && !defined(vsnprintf)
1960
#define vsnprintf _vsnprintf
1961
#endif
1962
1963
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1964
1
{
1965
1
    va_list args;
1966
1
    va_start(args, fmt);
1967
#ifdef IMGUI_USE_STB_SPRINTF
1968
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1969
#else
1970
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1971
1
#endif
1972
1
    va_end(args);
1973
1
    if (buf == NULL)
1974
0
        return w;
1975
1
    if (w == -1 || w >= (int)buf_size)
1976
0
        w = (int)buf_size - 1;
1977
1
    buf[w] = 0;
1978
1
    return w;
1979
1
}
1980
1981
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1982
49.0k
{
1983
#ifdef IMGUI_USE_STB_SPRINTF
1984
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1985
#else
1986
49.0k
    int w = vsnprintf(buf, buf_size, fmt, args);
1987
49.0k
#endif
1988
49.0k
    if (buf == NULL)
1989
0
        return w;
1990
49.0k
    if (w == -1 || w >= (int)buf_size)
1991
0
        w = (int)buf_size - 1;
1992
49.0k
    buf[w] = 0;
1993
49.0k
    return w;
1994
49.0k
}
1995
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1996
1997
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1998
49.0k
{
1999
49.0k
    va_list args;
2000
49.0k
    va_start(args, fmt);
2001
49.0k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2002
49.0k
    va_end(args);
2003
49.0k
}
2004
2005
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2006
49.0k
{
2007
49.0k
    ImGuiContext& g = *GImGui;
2008
49.0k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2009
0
    {
2010
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2011
0
        if (buf == NULL)
2012
0
            buf = "(null)";
2013
0
        *out_buf = buf;
2014
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2015
0
    }
2016
49.0k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2017
0
    {
2018
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2019
0
        const char* buf = va_arg(args, const char*);
2020
0
        if (buf == NULL)
2021
0
        {
2022
0
            buf = "(null)";
2023
0
            buf_len = ImMin(buf_len, 6);
2024
0
        }
2025
0
        *out_buf = buf;
2026
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2027
0
    }
2028
49.0k
    else
2029
49.0k
    {
2030
49.0k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2031
49.0k
        *out_buf = g.TempBuffer.Data;
2032
49.0k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2033
49.0k
    }
2034
49.0k
}
2035
2036
// CRC32 needs a 1KB lookup table (not cache friendly)
2037
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2038
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2039
static const ImU32 GCrc32LookupTable[256] =
2040
{
2041
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2042
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2043
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2044
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2045
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2046
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2047
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2048
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2049
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2050
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2051
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2052
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2053
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2054
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2055
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2056
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2057
};
2058
2059
// Known size hash
2060
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2061
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2062
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2063
49.0k
{
2064
49.0k
    ImU32 crc = ~seed;
2065
49.0k
    const unsigned char* data = (const unsigned char*)data_p;
2066
49.0k
    const ImU32* crc32_lut = GCrc32LookupTable;
2067
245k
    while (data_size-- != 0)
2068
196k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2069
49.0k
    return ~crc;
2070
49.0k
}
2071
2072
// Zero-terminated string hash, with support for ### to reset back to seed value
2073
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2074
// Because this syntax is rarely used we are optimizing for the common case.
2075
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2076
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2077
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2078
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2079
643k
{
2080
643k
    seed = ~seed;
2081
643k
    ImU32 crc = seed;
2082
643k
    const unsigned char* data = (const unsigned char*)data_p;
2083
643k
    const ImU32* crc32_lut = GCrc32LookupTable;
2084
643k
    if (data_size != 0)
2085
0
    {
2086
0
        while (data_size-- != 0)
2087
0
        {
2088
0
            unsigned char c = *data++;
2089
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2090
0
                crc = seed;
2091
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2092
0
        }
2093
0
    }
2094
643k
    else
2095
643k
    {
2096
8.69M
        while (unsigned char c = *data++)
2097
8.04M
        {
2098
8.04M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2099
69.6k
                crc = seed;
2100
8.04M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2101
8.04M
        }
2102
643k
    }
2103
643k
    return ~crc;
2104
643k
}
2105
2106
//-----------------------------------------------------------------------------
2107
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2108
//-----------------------------------------------------------------------------
2109
2110
// Default file functions
2111
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2112
2113
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2114
0
{
2115
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2116
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2117
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2118
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2119
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2120
    ImGuiContext& g = *GImGui;
2121
    g.TempBuffer.reserve((filename_wsize + mode_wsize) * sizeof(wchar_t));
2122
    wchar_t* buf = (wchar_t*)(void*)g.TempBuffer.Data;
2123
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2124
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2125
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2126
#else
2127
0
    return fopen(filename, mode);
2128
0
#endif
2129
0
}
2130
2131
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2132
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2133
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2134
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2135
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2136
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2137
2138
// Helper: Load file content into memory
2139
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2140
// This can't really be used with "rt" because fseek size won't match read size.
2141
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2142
0
{
2143
0
    IM_ASSERT(filename && mode);
2144
0
    if (out_file_size)
2145
0
        *out_file_size = 0;
2146
2147
0
    ImFileHandle f;
2148
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2149
0
        return NULL;
2150
2151
0
    size_t file_size = (size_t)ImFileGetSize(f);
2152
0
    if (file_size == (size_t)-1)
2153
0
    {
2154
0
        ImFileClose(f);
2155
0
        return NULL;
2156
0
    }
2157
2158
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2159
0
    if (file_data == NULL)
2160
0
    {
2161
0
        ImFileClose(f);
2162
0
        return NULL;
2163
0
    }
2164
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2165
0
    {
2166
0
        ImFileClose(f);
2167
0
        IM_FREE(file_data);
2168
0
        return NULL;
2169
0
    }
2170
0
    if (padding_bytes > 0)
2171
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2172
2173
0
    ImFileClose(f);
2174
0
    if (out_file_size)
2175
0
        *out_file_size = file_size;
2176
2177
0
    return file_data;
2178
0
}
2179
2180
//-----------------------------------------------------------------------------
2181
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2182
//-----------------------------------------------------------------------------
2183
2184
IM_MSVC_RUNTIME_CHECKS_OFF
2185
2186
// Convert UTF-8 to 32-bit character, process single character input.
2187
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2188
// We handle UTF-8 decoding error by skipping forward.
2189
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2190
4.08M
{
2191
4.08M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2192
4.08M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2193
4.08M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2194
4.08M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2195
4.08M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2196
4.08M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2197
4.08M
    int wanted = len + (len ? 0 : 1);
2198
2199
4.08M
    if (in_text_end == NULL)
2200
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2201
2202
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2203
    // so it is fast even with excessive branching.
2204
4.08M
    unsigned char s[4];
2205
4.08M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2206
4.08M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2207
4.08M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2208
4.08M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2209
2210
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2211
4.08M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2212
4.08M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2213
4.08M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2214
4.08M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2215
4.08M
    *out_char >>= shiftc[len];
2216
2217
    // Accumulate the various error conditions.
2218
4.08M
    int e = 0;
2219
4.08M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2220
4.08M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2221
4.08M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2222
4.08M
    e |= (s[1] & 0xc0) >> 2;
2223
4.08M
    e |= (s[2] & 0xc0) >> 4;
2224
4.08M
    e |= (s[3]       ) >> 6;
2225
4.08M
    e ^= 0x2a; // top two bits of each tail byte correct?
2226
4.08M
    e >>= shifte[len];
2227
2228
4.08M
    if (e)
2229
4.80k
    {
2230
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2231
        // One byte is consumed in case of invalid first byte of in_text.
2232
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2233
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2234
4.80k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2235
4.80k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2236
4.80k
    }
2237
2238
4.08M
    return wanted;
2239
4.08M
}
2240
2241
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2242
0
{
2243
0
    ImWchar* buf_out = buf;
2244
0
    ImWchar* buf_end = buf + buf_size;
2245
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2246
0
    {
2247
0
        unsigned int c;
2248
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2249
0
        *buf_out++ = (ImWchar)c;
2250
0
    }
2251
0
    *buf_out = 0;
2252
0
    if (in_text_remaining)
2253
0
        *in_text_remaining = in_text;
2254
0
    return (int)(buf_out - buf);
2255
0
}
2256
2257
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2258
0
{
2259
0
    int char_count = 0;
2260
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2261
0
    {
2262
0
        unsigned int c;
2263
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2264
0
        char_count++;
2265
0
    }
2266
0
    return char_count;
2267
0
}
2268
2269
// Based on stb_to_utf8() from github.com/nothings/stb/
2270
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2271
0
{
2272
0
    if (c < 0x80)
2273
0
    {
2274
0
        buf[0] = (char)c;
2275
0
        return 1;
2276
0
    }
2277
0
    if (c < 0x800)
2278
0
    {
2279
0
        if (buf_size < 2) return 0;
2280
0
        buf[0] = (char)(0xc0 + (c >> 6));
2281
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2282
0
        return 2;
2283
0
    }
2284
0
    if (c < 0x10000)
2285
0
    {
2286
0
        if (buf_size < 3) return 0;
2287
0
        buf[0] = (char)(0xe0 + (c >> 12));
2288
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2289
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2290
0
        return 3;
2291
0
    }
2292
0
    if (c <= 0x10FFFF)
2293
0
    {
2294
0
        if (buf_size < 4) return 0;
2295
0
        buf[0] = (char)(0xf0 + (c >> 18));
2296
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2297
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2298
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2299
0
        return 4;
2300
0
    }
2301
    // Invalid code point, the max unicode is 0x10FFFF
2302
0
    return 0;
2303
0
}
2304
2305
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2306
0
{
2307
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2308
0
    out_buf[count] = 0;
2309
0
    return out_buf;
2310
0
}
2311
2312
// Not optimal but we very rarely use this function.
2313
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2314
0
{
2315
0
    unsigned int unused = 0;
2316
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2317
0
}
2318
2319
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2320
0
{
2321
0
    if (c < 0x80) return 1;
2322
0
    if (c < 0x800) return 2;
2323
0
    if (c < 0x10000) return 3;
2324
0
    if (c <= 0x10FFFF) return 4;
2325
0
    return 3;
2326
0
}
2327
2328
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2329
0
{
2330
0
    char* buf_p = out_buf;
2331
0
    const char* buf_end = out_buf + out_buf_size;
2332
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2333
0
    {
2334
0
        unsigned int c = (unsigned int)(*in_text++);
2335
0
        if (c < 0x80)
2336
0
            *buf_p++ = (char)c;
2337
0
        else
2338
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2339
0
    }
2340
0
    *buf_p = 0;
2341
0
    return (int)(buf_p - out_buf);
2342
0
}
2343
2344
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2345
0
{
2346
0
    int bytes_count = 0;
2347
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2348
0
    {
2349
0
        unsigned int c = (unsigned int)(*in_text++);
2350
0
        if (c < 0x80)
2351
0
            bytes_count++;
2352
0
        else
2353
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2354
0
    }
2355
0
    return bytes_count;
2356
0
}
2357
2358
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2359
0
{
2360
0
    while (in_text_curr > in_text_start)
2361
0
    {
2362
0
        in_text_curr--;
2363
0
        if ((*in_text_curr & 0xC0) != 0x80)
2364
0
            return in_text_curr;
2365
0
    }
2366
0
    return in_text_start;
2367
0
}
2368
2369
IM_MSVC_RUNTIME_CHECKS_RESTORE
2370
2371
//-----------------------------------------------------------------------------
2372
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2373
// Note: The Convert functions are early design which are not consistent with other API.
2374
//-----------------------------------------------------------------------------
2375
2376
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2377
0
{
2378
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2379
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2380
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2381
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2382
0
    return IM_COL32(r, g, b, 0xFF);
2383
0
}
2384
2385
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2386
198k
{
2387
198k
    float s = 1.0f / 255.0f;
2388
198k
    return ImVec4(
2389
198k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2390
198k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2391
198k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2392
198k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2393
198k
}
2394
2395
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2396
1.15M
{
2397
1.15M
    ImU32 out;
2398
1.15M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2399
1.15M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2400
1.15M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2401
1.15M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2402
1.15M
    return out;
2403
1.15M
}
2404
2405
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2406
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2407
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2408
0
{
2409
0
    float K = 0.f;
2410
0
    if (g < b)
2411
0
    {
2412
0
        ImSwap(g, b);
2413
0
        K = -1.f;
2414
0
    }
2415
0
    if (r < g)
2416
0
    {
2417
0
        ImSwap(r, g);
2418
0
        K = -2.f / 6.f - K;
2419
0
    }
2420
2421
0
    const float chroma = r - (g < b ? g : b);
2422
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2423
0
    out_s = chroma / (r + 1e-20f);
2424
0
    out_v = r;
2425
0
}
2426
2427
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2428
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2429
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2430
0
{
2431
0
    if (s == 0.0f)
2432
0
    {
2433
        // gray
2434
0
        out_r = out_g = out_b = v;
2435
0
        return;
2436
0
    }
2437
2438
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2439
0
    int   i = (int)h;
2440
0
    float f = h - (float)i;
2441
0
    float p = v * (1.0f - s);
2442
0
    float q = v * (1.0f - s * f);
2443
0
    float t = v * (1.0f - s * (1.0f - f));
2444
2445
0
    switch (i)
2446
0
    {
2447
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2448
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2449
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2450
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2451
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2452
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2453
0
    }
2454
0
}
2455
2456
//-----------------------------------------------------------------------------
2457
// [SECTION] ImGuiStorage
2458
// Helper: Key->value storage
2459
//-----------------------------------------------------------------------------
2460
2461
// std::lower_bound but without the bullshit
2462
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2463
188k
{
2464
188k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2465
188k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2466
188k
    size_t count = (size_t)(last - first);
2467
565k
    while (count > 0)
2468
376k
    {
2469
376k
        size_t count2 = count >> 1;
2470
376k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2471
376k
        if (mid->key < key)
2472
118k
        {
2473
118k
            first = ++mid;
2474
118k
            count -= count2 + 1;
2475
118k
        }
2476
258k
        else
2477
258k
        {
2478
258k
            count = count2;
2479
258k
        }
2480
376k
    }
2481
188k
    return first;
2482
188k
}
2483
2484
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2485
void ImGuiStorage::BuildSortByKey()
2486
0
{
2487
0
    struct StaticFunc
2488
0
    {
2489
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2490
0
        {
2491
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2492
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2493
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2494
0
            return 0;
2495
0
        }
2496
0
    };
2497
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2498
0
}
2499
2500
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2501
0
{
2502
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2503
0
    if (it == Data.end() || it->key != key)
2504
0
        return default_val;
2505
0
    return it->val_i;
2506
0
}
2507
2508
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2509
0
{
2510
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2511
0
}
2512
2513
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2514
0
{
2515
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2516
0
    if (it == Data.end() || it->key != key)
2517
0
        return default_val;
2518
0
    return it->val_f;
2519
0
}
2520
2521
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2522
188k
{
2523
188k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2524
188k
    if (it == Data.end() || it->key != key)
2525
3
        return NULL;
2526
188k
    return it->val_p;
2527
188k
}
2528
2529
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2530
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2531
0
{
2532
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2533
0
    if (it == Data.end() || it->key != key)
2534
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2535
0
    return &it->val_i;
2536
0
}
2537
2538
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2539
0
{
2540
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2541
0
}
2542
2543
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2544
0
{
2545
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2546
0
    if (it == Data.end() || it->key != key)
2547
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2548
0
    return &it->val_f;
2549
0
}
2550
2551
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2552
0
{
2553
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2554
0
    if (it == Data.end() || it->key != key)
2555
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2556
0
    return &it->val_p;
2557
0
}
2558
2559
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2560
void ImGuiStorage::SetInt(ImGuiID key, int val)
2561
0
{
2562
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2563
0
    if (it == Data.end() || it->key != key)
2564
0
        Data.insert(it, ImGuiStoragePair(key, val));
2565
0
    else
2566
0
        it->val_i = val;
2567
0
}
2568
2569
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2570
0
{
2571
0
    SetInt(key, val ? 1 : 0);
2572
0
}
2573
2574
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2575
0
{
2576
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2577
0
    if (it == Data.end() || it->key != key)
2578
0
        Data.insert(it, ImGuiStoragePair(key, val));
2579
0
    else
2580
0
        it->val_f = val;
2581
0
}
2582
2583
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2584
3
{
2585
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2586
3
    if (it == Data.end() || it->key != key)
2587
3
        Data.insert(it, ImGuiStoragePair(key, val));
2588
0
    else
2589
0
        it->val_p = val;
2590
3
}
2591
2592
void ImGuiStorage::SetAllInt(int v)
2593
0
{
2594
0
    for (int i = 0; i < Data.Size; i++)
2595
0
        Data[i].val_i = v;
2596
0
}
2597
2598
//-----------------------------------------------------------------------------
2599
// [SECTION] ImGuiTextFilter
2600
//-----------------------------------------------------------------------------
2601
2602
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2603
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2604
0
{
2605
0
    InputBuf[0] = 0;
2606
0
    CountGrep = 0;
2607
0
    if (default_filter)
2608
0
    {
2609
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2610
0
        Build();
2611
0
    }
2612
0
}
2613
2614
bool ImGuiTextFilter::Draw(const char* label, float width)
2615
0
{
2616
0
    if (width != 0.0f)
2617
0
        ImGui::SetNextItemWidth(width);
2618
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2619
0
    if (value_changed)
2620
0
        Build();
2621
0
    return value_changed;
2622
0
}
2623
2624
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2625
0
{
2626
0
    out->resize(0);
2627
0
    const char* wb = b;
2628
0
    const char* we = wb;
2629
0
    while (we < e)
2630
0
    {
2631
0
        if (*we == separator)
2632
0
        {
2633
0
            out->push_back(ImGuiTextRange(wb, we));
2634
0
            wb = we + 1;
2635
0
        }
2636
0
        we++;
2637
0
    }
2638
0
    if (wb != we)
2639
0
        out->push_back(ImGuiTextRange(wb, we));
2640
0
}
2641
2642
void ImGuiTextFilter::Build()
2643
0
{
2644
0
    Filters.resize(0);
2645
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2646
0
    input_range.split(',', &Filters);
2647
2648
0
    CountGrep = 0;
2649
0
    for (ImGuiTextRange& f : Filters)
2650
0
    {
2651
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2652
0
            f.b++;
2653
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2654
0
            f.e--;
2655
0
        if (f.empty())
2656
0
            continue;
2657
0
        if (f.b[0] != '-')
2658
0
            CountGrep += 1;
2659
0
    }
2660
0
}
2661
2662
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2663
0
{
2664
0
    if (Filters.empty())
2665
0
        return true;
2666
2667
0
    if (text == NULL)
2668
0
        text = "";
2669
2670
0
    for (const ImGuiTextRange& f : Filters)
2671
0
    {
2672
0
        if (f.empty())
2673
0
            continue;
2674
0
        if (f.b[0] == '-')
2675
0
        {
2676
            // Subtract
2677
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2678
0
                return false;
2679
0
        }
2680
0
        else
2681
0
        {
2682
            // Grep
2683
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2684
0
                return true;
2685
0
        }
2686
0
    }
2687
2688
    // Implicit * grep
2689
0
    if (CountGrep == 0)
2690
0
        return true;
2691
2692
0
    return false;
2693
0
}
2694
2695
//-----------------------------------------------------------------------------
2696
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2697
//-----------------------------------------------------------------------------
2698
2699
// On some platform vsnprintf() takes va_list by reference and modifies it.
2700
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2701
#ifndef va_copy
2702
#if defined(__GNUC__) || defined(__clang__)
2703
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2704
#else
2705
#define va_copy(dest, src) (dest = src)
2706
#endif
2707
#endif
2708
2709
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2710
2711
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2712
0
{
2713
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2714
2715
    // Add zero-terminator the first time
2716
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2717
0
    const int needed_sz = write_off + len;
2718
0
    if (write_off + len >= Buf.Capacity)
2719
0
    {
2720
0
        int new_capacity = Buf.Capacity * 2;
2721
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2722
0
    }
2723
2724
0
    Buf.resize(needed_sz);
2725
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2726
0
    Buf[write_off - 1 + len] = 0;
2727
0
}
2728
2729
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2730
0
{
2731
0
    va_list args;
2732
0
    va_start(args, fmt);
2733
0
    appendfv(fmt, args);
2734
0
    va_end(args);
2735
0
}
2736
2737
// Helper: Text buffer for logging/accumulating text
2738
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2739
0
{
2740
0
    va_list args_copy;
2741
0
    va_copy(args_copy, args);
2742
2743
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2744
0
    if (len <= 0)
2745
0
    {
2746
0
        va_end(args_copy);
2747
0
        return;
2748
0
    }
2749
2750
    // Add zero-terminator the first time
2751
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2752
0
    const int needed_sz = write_off + len;
2753
0
    if (write_off + len >= Buf.Capacity)
2754
0
    {
2755
0
        int new_capacity = Buf.Capacity * 2;
2756
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2757
0
    }
2758
2759
0
    Buf.resize(needed_sz);
2760
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2761
0
    va_end(args_copy);
2762
0
}
2763
2764
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2765
0
{
2766
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2767
0
    if (old_size == new_size)
2768
0
        return;
2769
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2770
0
        LineOffsets.push_back(EndOffset);
2771
0
    const char* base_end = base + new_size;
2772
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2773
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2774
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2775
0
    EndOffset = ImMax(EndOffset, new_size);
2776
0
}
2777
2778
//-----------------------------------------------------------------------------
2779
// [SECTION] ImGuiListClipper
2780
//-----------------------------------------------------------------------------
2781
2782
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2783
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2784
static bool GetSkipItemForListClipping()
2785
0
{
2786
0
    ImGuiContext& g = *GImGui;
2787
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2788
0
}
2789
2790
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2791
0
{
2792
0
    if (ranges.Size - offset <= 1)
2793
0
        return;
2794
2795
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2796
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2797
0
        for (int i = offset; i < sort_end + offset; ++i)
2798
0
            if (ranges[i].Min > ranges[i + 1].Min)
2799
0
                ImSwap(ranges[i], ranges[i + 1]);
2800
2801
    // Now fuse ranges together as much as possible.
2802
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2803
0
    {
2804
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2805
0
        if (ranges[i - 1].Max < ranges[i].Min)
2806
0
            continue;
2807
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2808
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2809
0
        ranges.erase(ranges.Data + i);
2810
0
        i--;
2811
0
    }
2812
0
}
2813
2814
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2815
0
{
2816
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2817
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2818
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2819
0
    ImGuiContext& g = *GImGui;
2820
0
    ImGuiWindow* window = g.CurrentWindow;
2821
0
    float off_y = pos_y - window->DC.CursorPos.y;
2822
0
    window->DC.CursorPos.y = pos_y;
2823
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2824
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2825
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2826
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2827
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2828
0
    if (ImGuiTable* table = g.CurrentTable)
2829
0
    {
2830
0
        if (table->IsInsideRow)
2831
0
            ImGui::TableEndRow(table);
2832
0
        table->RowPosY2 = window->DC.CursorPos.y;
2833
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2834
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2835
0
        table->RowBgColorCounter += row_increase;
2836
0
    }
2837
0
}
2838
2839
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2840
0
{
2841
    // StartPosY starts from ItemsFrozen hence the subtraction
2842
    // Perform the add and multiply with double to allow seeking through larger ranges
2843
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2844
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2845
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2846
0
}
2847
2848
ImGuiListClipper::ImGuiListClipper()
2849
0
{
2850
0
    memset(this, 0, sizeof(*this));
2851
0
}
2852
2853
ImGuiListClipper::~ImGuiListClipper()
2854
0
{
2855
0
    End();
2856
0
}
2857
2858
void ImGuiListClipper::Begin(int items_count, float items_height)
2859
0
{
2860
0
    if (Ctx == NULL)
2861
0
        Ctx = ImGui::GetCurrentContext();
2862
2863
0
    ImGuiContext& g = *Ctx;
2864
0
    ImGuiWindow* window = g.CurrentWindow;
2865
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2866
2867
0
    if (ImGuiTable* table = g.CurrentTable)
2868
0
        if (table->IsInsideRow)
2869
0
            ImGui::TableEndRow(table);
2870
2871
0
    StartPosY = window->DC.CursorPos.y;
2872
0
    ItemsHeight = items_height;
2873
0
    ItemsCount = items_count;
2874
0
    DisplayStart = -1;
2875
0
    DisplayEnd = 0;
2876
2877
    // Acquire temporary buffer
2878
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2879
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2880
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2881
0
    data->Reset(this);
2882
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2883
0
    TempData = data;
2884
0
}
2885
2886
void ImGuiListClipper::End()
2887
0
{
2888
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2889
0
    {
2890
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2891
0
        ImGuiContext& g = *Ctx;
2892
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2893
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2894
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2895
2896
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2897
0
        IM_ASSERT(data->ListClipper == this);
2898
0
        data->StepNo = data->Ranges.Size;
2899
0
        if (--g.ClipperTempDataStacked > 0)
2900
0
        {
2901
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2902
0
            data->ListClipper->TempData = data;
2903
0
        }
2904
0
        TempData = NULL;
2905
0
    }
2906
0
    ItemsCount = -1;
2907
0
}
2908
2909
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2910
0
{
2911
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2912
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2913
0
    IM_ASSERT(item_begin <= item_end);
2914
0
    if (item_begin < item_end)
2915
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2916
0
}
2917
2918
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2919
0
{
2920
0
    ImGuiContext& g = *clipper->Ctx;
2921
0
    ImGuiWindow* window = g.CurrentWindow;
2922
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2923
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2924
2925
0
    ImGuiTable* table = g.CurrentTable;
2926
0
    if (table && table->IsInsideRow)
2927
0
        ImGui::TableEndRow(table);
2928
2929
    // No items
2930
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2931
0
        return false;
2932
2933
    // While we are in frozen row state, keep displaying items one by one, unclipped
2934
    // FIXME: Could be stored as a table-agnostic state.
2935
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2936
0
    {
2937
0
        clipper->DisplayStart = data->ItemsFrozen;
2938
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2939
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2940
0
            data->ItemsFrozen++;
2941
0
        return true;
2942
0
    }
2943
2944
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2945
0
    bool calc_clipping = false;
2946
0
    if (data->StepNo == 0)
2947
0
    {
2948
0
        clipper->StartPosY = window->DC.CursorPos.y;
2949
0
        if (clipper->ItemsHeight <= 0.0f)
2950
0
        {
2951
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2952
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2953
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2954
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2955
0
            data->StepNo = 1;
2956
0
            return true;
2957
0
        }
2958
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2959
0
    }
2960
2961
    // Step 1: Let the clipper infer height from first range
2962
0
    if (clipper->ItemsHeight <= 0.0f)
2963
0
    {
2964
0
        IM_ASSERT(data->StepNo == 1);
2965
0
        if (table)
2966
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2967
2968
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2969
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2970
0
        if (affected_by_floating_point_precision)
2971
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2972
2973
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2974
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2975
0
    }
2976
2977
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2978
0
    const int already_submitted = clipper->DisplayEnd;
2979
0
    if (calc_clipping)
2980
0
    {
2981
0
        if (g.LogEnabled)
2982
0
        {
2983
            // If logging is active, do not perform any clipping
2984
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2985
0
        }
2986
0
        else
2987
0
        {
2988
            // Add range selected to be included for navigation
2989
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2990
0
            if (is_nav_request)
2991
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2992
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
2993
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2994
2995
            // Add focused/active item
2996
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2997
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2998
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2999
3000
            // Add visible range
3001
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3002
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3003
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3004
0
        }
3005
3006
        // Convert position ranges to item index ranges
3007
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3008
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3009
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3010
0
        for (ImGuiListClipperRange& range : data->Ranges)
3011
0
            if (range.PosToIndexConvert)
3012
0
            {
3013
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3014
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3015
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3016
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3017
0
                range.PosToIndexConvert = false;
3018
0
            }
3019
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3020
0
    }
3021
3022
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3023
0
    while (data->StepNo < data->Ranges.Size)
3024
0
    {
3025
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3026
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3027
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3028
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3029
0
        data->StepNo++;
3030
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3031
0
            continue;
3032
0
        return true;
3033
0
    }
3034
3035
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3036
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3037
0
    if (clipper->ItemsCount < INT_MAX)
3038
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3039
3040
0
    return false;
3041
0
}
3042
3043
bool ImGuiListClipper::Step()
3044
0
{
3045
0
    ImGuiContext& g = *Ctx;
3046
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3047
0
    bool ret = ImGuiListClipper_StepInternal(this);
3048
0
    if (ret && (DisplayStart == DisplayEnd))
3049
0
        ret = false;
3050
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3051
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3052
0
    if (need_items_height && ItemsHeight > 0.0f)
3053
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3054
0
    if (ret)
3055
0
    {
3056
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3057
0
    }
3058
0
    else
3059
0
    {
3060
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3061
0
        End();
3062
0
    }
3063
0
    return ret;
3064
0
}
3065
3066
//-----------------------------------------------------------------------------
3067
// [SECTION] STYLING
3068
//-----------------------------------------------------------------------------
3069
3070
ImGuiStyle& ImGui::GetStyle()
3071
129k
{
3072
129k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3073
129k
    return GImGui->Style;
3074
129k
}
3075
3076
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3077
1.02M
{
3078
1.02M
    ImGuiStyle& style = GImGui->Style;
3079
1.02M
    ImVec4 c = style.Colors[idx];
3080
1.02M
    c.w *= style.Alpha * alpha_mul;
3081
1.02M
    return ColorConvertFloat4ToU32(c);
3082
1.02M
}
3083
3084
ImU32 ImGui::GetColorU32(const ImVec4& col)
3085
0
{
3086
0
    ImGuiStyle& style = GImGui->Style;
3087
0
    ImVec4 c = col;
3088
0
    c.w *= style.Alpha;
3089
0
    return ColorConvertFloat4ToU32(c);
3090
0
}
3091
3092
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3093
0
{
3094
0
    ImGuiStyle& style = GImGui->Style;
3095
0
    return style.Colors[idx];
3096
0
}
3097
3098
ImU32 ImGui::GetColorU32(ImU32 col)
3099
0
{
3100
0
    ImGuiStyle& style = GImGui->Style;
3101
0
    if (style.Alpha >= 1.0f)
3102
0
        return col;
3103
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3104
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3105
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3106
0
}
3107
3108
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3109
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3110
0
{
3111
0
    ImGuiContext& g = *GImGui;
3112
0
    ImGuiColorMod backup;
3113
0
    backup.Col = idx;
3114
0
    backup.BackupValue = g.Style.Colors[idx];
3115
0
    g.ColorStack.push_back(backup);
3116
0
    if (g.DebugFlashStyleColorIdx != idx)
3117
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3118
0
}
3119
3120
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3121
69.6k
{
3122
69.6k
    ImGuiContext& g = *GImGui;
3123
69.6k
    ImGuiColorMod backup;
3124
69.6k
    backup.Col = idx;
3125
69.6k
    backup.BackupValue = g.Style.Colors[idx];
3126
69.6k
    g.ColorStack.push_back(backup);
3127
69.6k
    if (g.DebugFlashStyleColorIdx != idx)
3128
69.6k
        g.Style.Colors[idx] = col;
3129
69.6k
}
3130
3131
void ImGui::PopStyleColor(int count)
3132
69.6k
{
3133
69.6k
    ImGuiContext& g = *GImGui;
3134
69.6k
    if (g.ColorStack.Size < count)
3135
0
    {
3136
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3137
0
        count = g.ColorStack.Size;
3138
0
    }
3139
139k
    while (count > 0)
3140
69.6k
    {
3141
69.6k
        ImGuiColorMod& backup = g.ColorStack.back();
3142
69.6k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3143
69.6k
        g.ColorStack.pop_back();
3144
69.6k
        count--;
3145
69.6k
    }
3146
69.6k
}
3147
3148
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3149
{
3150
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3151
};
3152
3153
static const ImGuiDataVarInfo GStyleVarInfo[] =
3154
{
3155
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                 // ImGuiStyleVar_Alpha
3156
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },         // ImGuiStyleVar_DisabledAlpha
3157
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },         // ImGuiStyleVar_WindowPadding
3158
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },        // ImGuiStyleVar_WindowRounding
3159
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },      // ImGuiStyleVar_WindowBorderSize
3160
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },         // ImGuiStyleVar_WindowMinSize
3161
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },      // ImGuiStyleVar_WindowTitleAlign
3162
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },         // ImGuiStyleVar_ChildRounding
3163
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },       // ImGuiStyleVar_ChildBorderSize
3164
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },         // ImGuiStyleVar_PopupRounding
3165
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },       // ImGuiStyleVar_PopupBorderSize
3166
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },          // ImGuiStyleVar_FramePadding
3167
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },         // ImGuiStyleVar_FrameRounding
3168
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },       // ImGuiStyleVar_FrameBorderSize
3169
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },           // ImGuiStyleVar_ItemSpacing
3170
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },      // ImGuiStyleVar_ItemInnerSpacing
3171
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },         // ImGuiStyleVar_IndentSpacing
3172
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },           // ImGuiStyleVar_CellPadding
3173
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },         // ImGuiStyleVar_ScrollbarSize
3174
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },     // ImGuiStyleVar_ScrollbarRounding
3175
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },           // ImGuiStyleVar_GrabMinSize
3176
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },          // ImGuiStyleVar_GrabRounding
3177
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },           // ImGuiStyleVar_TabRounding
3178
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },      // ImGuiStyleVar_TabBarBorderSize
3179
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },       // ImGuiStyleVar_ButtonTextAlign
3180
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },   // ImGuiStyleVar_SelectableTextAlign
3181
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3182
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },    // ImGuiStyleVar_SeparatorTextAlign
3183
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },  // ImGuiStyleVar_SeparatorTextPadding
3184
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },  // ImGuiStyleVar_DockingSeparatorSize
3185
};
3186
3187
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3188
139k
{
3189
139k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3190
139k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3191
139k
    return &GStyleVarInfo[idx];
3192
139k
}
3193
3194
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3195
0
{
3196
0
    ImGuiContext& g = *GImGui;
3197
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3198
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3199
0
    {
3200
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3201
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3202
0
        *pvar = val;
3203
0
        return;
3204
0
    }
3205
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3206
0
}
3207
3208
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3209
69.6k
{
3210
69.6k
    ImGuiContext& g = *GImGui;
3211
69.6k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3212
69.6k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3213
69.6k
    {
3214
69.6k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3215
69.6k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3216
69.6k
        *pvar = val;
3217
69.6k
        return;
3218
69.6k
    }
3219
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3220
0
}
3221
3222
void ImGui::PopStyleVar(int count)
3223
69.6k
{
3224
69.6k
    ImGuiContext& g = *GImGui;
3225
69.6k
    if (g.StyleVarStack.Size < count)
3226
0
    {
3227
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3228
0
        count = g.StyleVarStack.Size;
3229
0
    }
3230
139k
    while (count > 0)
3231
69.6k
    {
3232
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3233
69.6k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3234
69.6k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3235
69.6k
        void* data = info->GetVarPtr(&g.Style);
3236
69.6k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3237
69.6k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3238
69.6k
        g.StyleVarStack.pop_back();
3239
69.6k
        count--;
3240
69.6k
    }
3241
69.6k
}
3242
3243
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3244
0
{
3245
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3246
0
    switch (idx)
3247
0
    {
3248
0
    case ImGuiCol_Text: return "Text";
3249
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3250
0
    case ImGuiCol_WindowBg: return "WindowBg";
3251
0
    case ImGuiCol_ChildBg: return "ChildBg";
3252
0
    case ImGuiCol_PopupBg: return "PopupBg";
3253
0
    case ImGuiCol_Border: return "Border";
3254
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3255
0
    case ImGuiCol_FrameBg: return "FrameBg";
3256
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3257
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3258
0
    case ImGuiCol_TitleBg: return "TitleBg";
3259
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3260
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3261
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3262
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3263
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3264
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3265
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3266
0
    case ImGuiCol_CheckMark: return "CheckMark";
3267
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3268
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3269
0
    case ImGuiCol_Button: return "Button";
3270
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3271
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3272
0
    case ImGuiCol_Header: return "Header";
3273
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3274
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3275
0
    case ImGuiCol_Separator: return "Separator";
3276
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3277
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3278
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3279
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3280
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3281
0
    case ImGuiCol_Tab: return "Tab";
3282
0
    case ImGuiCol_TabHovered: return "TabHovered";
3283
0
    case ImGuiCol_TabActive: return "TabActive";
3284
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3285
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3286
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3287
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3288
0
    case ImGuiCol_PlotLines: return "PlotLines";
3289
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3290
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3291
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3292
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3293
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3294
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3295
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3296
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3297
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3298
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3299
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3300
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3301
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3302
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3303
0
    }
3304
0
    IM_ASSERT(0);
3305
0
    return "Unknown";
3306
0
}
3307
3308
3309
//-----------------------------------------------------------------------------
3310
// [SECTION] RENDER HELPERS
3311
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3312
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3313
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3314
//-----------------------------------------------------------------------------
3315
3316
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3317
278k
{
3318
278k
    const char* text_display_end = text;
3319
278k
    if (!text_end)
3320
278k
        text_end = (const char*)-1;
3321
3322
2.50M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3323
2.22M
        text_display_end++;
3324
278k
    return text_display_end;
3325
278k
}
3326
3327
// Internal ImGui functions to render text
3328
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3329
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3330
0
{
3331
0
    ImGuiContext& g = *GImGui;
3332
0
    ImGuiWindow* window = g.CurrentWindow;
3333
3334
    // Hide anything after a '##' string
3335
0
    const char* text_display_end;
3336
0
    if (hide_text_after_hash)
3337
0
    {
3338
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3339
0
    }
3340
0
    else
3341
0
    {
3342
0
        if (!text_end)
3343
0
            text_end = text + strlen(text); // FIXME-OPT
3344
0
        text_display_end = text_end;
3345
0
    }
3346
3347
0
    if (text != text_display_end)
3348
0
    {
3349
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3350
0
        if (g.LogEnabled)
3351
0
            LogRenderedText(&pos, text, text_display_end);
3352
0
    }
3353
0
}
3354
3355
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3356
0
{
3357
0
    ImGuiContext& g = *GImGui;
3358
0
    ImGuiWindow* window = g.CurrentWindow;
3359
3360
0
    if (!text_end)
3361
0
        text_end = text + strlen(text); // FIXME-OPT
3362
3363
0
    if (text != text_end)
3364
0
    {
3365
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3366
0
        if (g.LogEnabled)
3367
0
            LogRenderedText(&pos, text, text_end);
3368
0
    }
3369
0
}
3370
3371
// Default clip_rect uses (pos_min,pos_max)
3372
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3373
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3374
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3375
// better advantage of the render function taking size into account for coarse clipping.
3376
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3377
139k
{
3378
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3379
139k
    ImVec2 pos = pos_min;
3380
139k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3381
3382
139k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3383
139k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3384
139k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3385
139k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3386
139k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3387
3388
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3389
139k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3390
139k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3391
3392
    // Render
3393
139k
    if (need_clipping)
3394
69.6k
    {
3395
69.6k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3396
69.6k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3397
69.6k
    }
3398
69.6k
    else
3399
69.6k
    {
3400
69.6k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3401
69.6k
    }
3402
139k
}
3403
3404
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3405
139k
{
3406
    // Hide anything after a '##' string
3407
139k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3408
139k
    const int text_len = (int)(text_display_end - text);
3409
139k
    if (text_len == 0)
3410
0
        return;
3411
3412
139k
    ImGuiContext& g = *GImGui;
3413
139k
    ImGuiWindow* window = g.CurrentWindow;
3414
139k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3415
139k
    if (g.LogEnabled)
3416
0
        LogRenderedText(&pos_min, text, text_display_end);
3417
139k
}
3418
3419
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3420
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3421
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3422
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3423
0
{
3424
0
    ImGuiContext& g = *GImGui;
3425
0
    if (text_end_full == NULL)
3426
0
        text_end_full = FindRenderedTextEnd(text);
3427
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3428
3429
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3430
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3431
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3432
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3433
0
    if (text_size.x > pos_max.x - pos_min.x)
3434
0
    {
3435
        // Hello wo...
3436
        // |       |   |
3437
        // min   max   ellipsis_max
3438
        //          <-> this is generally some padding value
3439
3440
0
        const ImFont* font = draw_list->_Data->Font;
3441
0
        const float font_size = draw_list->_Data->FontSize;
3442
0
        const float font_scale = font_size / font->FontSize;
3443
0
        const char* text_end_ellipsis = NULL;
3444
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3445
3446
        // We can now claim the space between pos_max.x and ellipsis_max.x
3447
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3448
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3449
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3450
0
        {
3451
            // Always display at least 1 character if there's no room for character + ellipsis
3452
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3453
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3454
0
        }
3455
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3456
0
        {
3457
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3458
0
            text_end_ellipsis--;
3459
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3460
0
        }
3461
3462
        // Render text, render ellipsis
3463
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3464
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3465
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3466
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3467
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3468
0
    }
3469
0
    else
3470
0
    {
3471
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3472
0
    }
3473
3474
0
    if (g.LogEnabled)
3475
0
        LogRenderedText(&pos_min, text, text_end_full);
3476
0
}
3477
3478
// Render a rectangle shaped with optional rounding and borders
3479
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3480
20.5k
{
3481
20.5k
    ImGuiContext& g = *GImGui;
3482
20.5k
    ImGuiWindow* window = g.CurrentWindow;
3483
20.5k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3484
20.5k
    const float border_size = g.Style.FrameBorderSize;
3485
20.5k
    if (border && border_size > 0.0f)
3486
20.5k
    {
3487
20.5k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3488
20.5k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3489
20.5k
    }
3490
20.5k
}
3491
3492
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3493
0
{
3494
0
    ImGuiContext& g = *GImGui;
3495
0
    ImGuiWindow* window = g.CurrentWindow;
3496
0
    const float border_size = g.Style.FrameBorderSize;
3497
0
    if (border_size > 0.0f)
3498
0
    {
3499
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3500
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3501
0
    }
3502
0
}
3503
3504
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3505
74.8k
{
3506
74.8k
    ImGuiContext& g = *GImGui;
3507
74.8k
    if (id != g.NavId)
3508
34.1k
        return;
3509
40.7k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3510
3.77k
        return;
3511
36.9k
    ImGuiWindow* window = g.CurrentWindow;
3512
36.9k
    if (window->DC.NavHideHighlightOneFrame)
3513
0
        return;
3514
3515
36.9k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3516
36.9k
    ImRect display_rect = bb;
3517
36.9k
    display_rect.ClipWith(window->ClipRect);
3518
36.9k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3519
11.0k
    {
3520
11.0k
        const float THICKNESS = 2.0f;
3521
11.0k
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3522
11.0k
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3523
11.0k
        bool fully_visible = window->ClipRect.Contains(display_rect);
3524
11.0k
        if (!fully_visible)
3525
6.32k
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3526
11.0k
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3527
11.0k
        if (!fully_visible)
3528
6.32k
            window->DrawList->PopClipRect();
3529
11.0k
    }
3530
36.9k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3531
25.8k
    {
3532
25.8k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3533
25.8k
    }
3534
36.9k
}
3535
3536
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3537
0
{
3538
0
    ImGuiContext& g = *GImGui;
3539
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3540
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3541
0
    for (ImGuiViewportP* viewport : g.Viewports)
3542
0
    {
3543
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3544
0
        ImVec2 offset, size, uv[4];
3545
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3546
0
            continue;
3547
0
        const ImVec2 pos = base_pos - offset;
3548
0
        const float scale = base_scale * viewport->DpiScale;
3549
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3550
0
            continue;
3551
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3552
0
        ImTextureID tex_id = font_atlas->TexID;
3553
0
        draw_list->PushTextureID(tex_id);
3554
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3555
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3556
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3557
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3558
0
        draw_list->PopTextureID();
3559
0
    }
3560
0
}
3561
3562
//-----------------------------------------------------------------------------
3563
// [SECTION] INITIALIZATION, SHUTDOWN
3564
//-----------------------------------------------------------------------------
3565
3566
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3567
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3568
ImGuiContext* ImGui::GetCurrentContext()
3569
1
{
3570
1
    return GImGui;
3571
1
}
3572
3573
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3574
1
{
3575
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3576
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3577
#else
3578
1
    GImGui = ctx;
3579
1
#endif
3580
1
}
3581
3582
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3583
0
{
3584
0
    GImAllocatorAllocFunc = alloc_func;
3585
0
    GImAllocatorFreeFunc = free_func;
3586
0
    GImAllocatorUserData = user_data;
3587
0
}
3588
3589
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3590
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3591
0
{
3592
0
    *p_alloc_func = GImAllocatorAllocFunc;
3593
0
    *p_free_func = GImAllocatorFreeFunc;
3594
0
    *p_user_data = GImAllocatorUserData;
3595
0
}
3596
3597
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3598
1
{
3599
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3600
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3601
1
    SetCurrentContext(ctx);
3602
1
    Initialize();
3603
1
    if (prev_ctx != NULL)
3604
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3605
1
    return ctx;
3606
1
}
3607
3608
void ImGui::DestroyContext(ImGuiContext* ctx)
3609
0
{
3610
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3611
0
    if (ctx == NULL) //-V1051
3612
0
        ctx = prev_ctx;
3613
0
    SetCurrentContext(ctx);
3614
0
    Shutdown();
3615
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3616
0
    IM_DELETE(ctx);
3617
0
}
3618
3619
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3620
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3621
{
3622
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3623
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3624
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3625
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3626
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3627
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3628
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3629
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3630
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3631
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3632
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3633
};
3634
3635
void ImGui::Initialize()
3636
1
{
3637
1
    ImGuiContext& g = *GImGui;
3638
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3639
3640
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3641
1
    {
3642
1
        ImGuiSettingsHandler ini_handler;
3643
1
        ini_handler.TypeName = "Window";
3644
1
        ini_handler.TypeHash = ImHashStr("Window");
3645
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3646
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3647
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3648
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3649
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3650
1
        AddSettingsHandler(&ini_handler);
3651
1
    }
3652
1
    TableSettingsAddSettingsHandler();
3653
3654
    // Setup default localization table
3655
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3656
3657
    // Setup default platform clipboard/IME handlers.
3658
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3659
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3660
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3661
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3662
3663
    // Create default viewport
3664
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3665
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3666
1
    viewport->Idx = 0;
3667
1
    viewport->PlatformWindowCreated = true;
3668
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3669
1
    g.Viewports.push_back(viewport);
3670
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3671
1
    g.ViewportCreatedCount++;
3672
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3673
3674
1
#ifdef IMGUI_HAS_DOCK
3675
    // Initialize Docking
3676
1
    DockContextInitialize(&g);
3677
1
#endif
3678
3679
1
    g.Initialized = true;
3680
1
}
3681
3682
// This function is merely here to free heap allocations.
3683
void ImGui::Shutdown()
3684
0
{
3685
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3686
0
    ImGuiContext& g = *GImGui;
3687
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3688
0
    {
3689
0
        g.IO.Fonts->Locked = false;
3690
0
        IM_DELETE(g.IO.Fonts);
3691
0
    }
3692
0
    g.IO.Fonts = NULL;
3693
0
    g.DrawListSharedData.TempBuffer.clear();
3694
3695
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3696
0
    if (!g.Initialized)
3697
0
        return;
3698
3699
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3700
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3701
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3702
3703
    // Destroy platform windows
3704
0
    DestroyPlatformWindows();
3705
3706
    // Shutdown extensions
3707
0
    DockContextShutdown(&g);
3708
3709
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3710
3711
    // Clear everything else
3712
0
    g.Windows.clear_delete();
3713
0
    g.WindowsFocusOrder.clear();
3714
0
    g.WindowsTempSortBuffer.clear();
3715
0
    g.CurrentWindow = NULL;
3716
0
    g.CurrentWindowStack.clear();
3717
0
    g.WindowsById.Clear();
3718
0
    g.NavWindow = NULL;
3719
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3720
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3721
0
    g.MovingWindow = NULL;
3722
3723
0
    g.KeysRoutingTable.Clear();
3724
3725
0
    g.ColorStack.clear();
3726
0
    g.StyleVarStack.clear();
3727
0
    g.FontStack.clear();
3728
0
    g.OpenPopupStack.clear();
3729
0
    g.BeginPopupStack.clear();
3730
0
    g.NavTreeNodeStack.clear();
3731
3732
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3733
0
    g.Viewports.clear_delete();
3734
3735
0
    g.TabBars.Clear();
3736
0
    g.CurrentTabBarStack.clear();
3737
0
    g.ShrinkWidthBuffer.clear();
3738
3739
0
    g.ClipperTempData.clear_destruct();
3740
3741
0
    g.Tables.Clear();
3742
0
    g.TablesTempData.clear_destruct();
3743
0
    g.DrawChannelsTempMergeBuffer.clear();
3744
3745
0
    g.ClipboardHandlerData.clear();
3746
0
    g.MenusIdSubmittedThisFrame.clear();
3747
0
    g.InputTextState.ClearFreeMemory();
3748
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3749
3750
0
    g.SettingsWindows.clear();
3751
0
    g.SettingsHandlers.clear();
3752
3753
0
    if (g.LogFile)
3754
0
    {
3755
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3756
0
        if (g.LogFile != stdout)
3757
0
#endif
3758
0
            ImFileClose(g.LogFile);
3759
0
        g.LogFile = NULL;
3760
0
    }
3761
0
    g.LogBuffer.clear();
3762
0
    g.DebugLogBuf.clear();
3763
0
    g.DebugLogIndex.clear();
3764
3765
0
    g.Initialized = false;
3766
0
}
3767
3768
// No specific ordering/dependency support, will see as needed
3769
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3770
0
{
3771
0
    ImGuiContext& g = *ctx;
3772
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3773
0
    g.Hooks.push_back(*hook);
3774
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3775
0
    return g.HookIdNext;
3776
0
}
3777
3778
// Deferred removal, avoiding issue with changing vector while iterating it
3779
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3780
0
{
3781
0
    ImGuiContext& g = *ctx;
3782
0
    IM_ASSERT(hook_id != 0);
3783
0
    for (ImGuiContextHook& hook : g.Hooks)
3784
0
        if (hook.HookId == hook_id)
3785
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3786
0
}
3787
3788
// Call context hooks (used by e.g. test engine)
3789
// We assume a small number of hooks so all stored in same array
3790
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3791
418k
{
3792
418k
    ImGuiContext& g = *ctx;
3793
418k
    for (ImGuiContextHook& hook : g.Hooks)
3794
0
        if (hook.Type == hook_type)
3795
0
            hook.Callback(&g, &hook);
3796
418k
}
3797
3798
3799
//-----------------------------------------------------------------------------
3800
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3801
//-----------------------------------------------------------------------------
3802
3803
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3804
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3805
3
{
3806
3
    memset(this, 0, sizeof(*this));
3807
3
    Ctx = ctx;
3808
3
    Name = ImStrdup(name);
3809
3
    NameBufLen = (int)strlen(name) + 1;
3810
3
    ID = ImHashStr(name);
3811
3
    IDStack.push_back(ID);
3812
3
    ViewportAllowPlatformMonitorExtend = -1;
3813
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3814
3
    MoveId = GetID("#MOVE");
3815
3
    TabId = GetID("#TAB");
3816
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3817
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3818
3
    AutoFitFramesX = AutoFitFramesY = -1;
3819
3
    AutoPosLastDirection = ImGuiDir_None;
3820
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3821
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3822
3
    LastFrameActive = -1;
3823
3
    LastFrameJustFocused = -1;
3824
3
    LastTimeActive = -1.0f;
3825
3
    FontWindowScale = FontDpiScale = 1.0f;
3826
3
    SettingsOffset = -1;
3827
3
    DockOrder = -1;
3828
3
    DrawList = &DrawListInst;
3829
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3830
3
    DrawList->_OwnerName = Name;
3831
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3832
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3833
3
}
3834
3835
ImGuiWindow::~ImGuiWindow()
3836
0
{
3837
0
    IM_ASSERT(DrawList == &DrawListInst);
3838
0
    IM_DELETE(Name);
3839
0
    ColumnsStorage.clear_destruct();
3840
0
}
3841
3842
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3843
336k
{
3844
336k
    ImGuiID seed = IDStack.back();
3845
336k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3846
336k
    ImGuiContext& g = *Ctx;
3847
336k
    if (g.DebugHookIdInfo == id)
3848
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3849
336k
    return id;
3850
336k
}
3851
3852
ImGuiID ImGuiWindow::GetID(const void* ptr)
3853
0
{
3854
0
    ImGuiID seed = IDStack.back();
3855
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3856
0
    ImGuiContext& g = *Ctx;
3857
0
    if (g.DebugHookIdInfo == id)
3858
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3859
0
    return id;
3860
0
}
3861
3862
ImGuiID ImGuiWindow::GetID(int n)
3863
49.0k
{
3864
49.0k
    ImGuiID seed = IDStack.back();
3865
49.0k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3866
49.0k
    ImGuiContext& g = *Ctx;
3867
49.0k
    if (g.DebugHookIdInfo == id)
3868
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3869
49.0k
    return id;
3870
49.0k
}
3871
3872
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3873
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3874
0
{
3875
0
    ImGuiID seed = IDStack.back();
3876
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3877
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3878
0
    return id;
3879
0
}
3880
3881
static void SetCurrentWindow(ImGuiWindow* window)
3882
376k
{
3883
376k
    ImGuiContext& g = *GImGui;
3884
376k
    g.CurrentWindow = window;
3885
376k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3886
376k
    if (window)
3887
307k
    {
3888
307k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3889
307k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3890
307k
    }
3891
376k
}
3892
3893
void ImGui::GcCompactTransientMiscBuffers()
3894
0
{
3895
0
    ImGuiContext& g = *GImGui;
3896
0
    g.ItemFlagsStack.clear();
3897
0
    g.GroupStack.clear();
3898
0
    TableGcCompactSettings();
3899
0
}
3900
3901
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3902
// Not freed:
3903
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3904
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3905
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3906
3
{
3907
3
    window->MemoryCompacted = true;
3908
3
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3909
3
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3910
3
    window->IDStack.clear();
3911
3
    window->DrawList->_ClearFreeMemory();
3912
3
    window->DC.ChildWindows.clear();
3913
3
    window->DC.ItemWidthStack.clear();
3914
3
    window->DC.TextWrapPosStack.clear();
3915
3
}
3916
3917
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3918
3
{
3919
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3920
    // The other buffers tends to amortize much faster.
3921
3
    window->MemoryCompacted = false;
3922
3
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3923
3
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3924
3
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3925
3
}
3926
3927
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3928
2.21k
{
3929
2.21k
    ImGuiContext& g = *GImGui;
3930
3931
    // Clear previous active id
3932
2.21k
    if (g.ActiveId != 0)
3933
461
    {
3934
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3935
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3936
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3937
461
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3938
0
        {
3939
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3940
0
            g.MovingWindow = NULL;
3941
0
        }
3942
3943
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3944
        // but since this is currently quite an exception we'll leave it as is.
3945
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3946
461
        if (g.InputTextState.ID == g.ActiveId)
3947
0
            InputTextDeactivateHook(g.ActiveId);
3948
461
    }
3949
3950
    // Set active id
3951
2.21k
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3952
2.21k
    if (g.ActiveIdIsJustActivated)
3953
823
    {
3954
823
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3955
823
        g.ActiveIdTimer = 0.0f;
3956
823
        g.ActiveIdHasBeenPressedBefore = false;
3957
823
        g.ActiveIdHasBeenEditedBefore = false;
3958
823
        g.ActiveIdMouseButton = -1;
3959
823
        if (id != 0)
3960
461
        {
3961
461
            g.LastActiveId = id;
3962
461
            g.LastActiveIdTimer = 0.0f;
3963
461
        }
3964
823
    }
3965
2.21k
    g.ActiveId = id;
3966
2.21k
    g.ActiveIdAllowOverlap = false;
3967
2.21k
    g.ActiveIdNoClearOnFocusLoss = false;
3968
2.21k
    g.ActiveIdWindow = window;
3969
2.21k
    g.ActiveIdHasBeenEditedThisFrame = false;
3970
2.21k
    if (id)
3971
461
    {
3972
461
        g.ActiveIdIsAlive = id;
3973
461
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3974
461
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3975
461
    }
3976
3977
    // Clear declaration of inputs claimed by the widget
3978
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3979
2.21k
    g.ActiveIdUsingNavDirMask = 0x00;
3980
2.21k
    g.ActiveIdUsingAllKeyboardKeys = false;
3981
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3982
    g.ActiveIdUsingNavInputMask = 0x00;
3983
#endif
3984
2.21k
}
3985
3986
void ImGui::ClearActiveID()
3987
1.75k
{
3988
1.75k
    SetActiveID(0, NULL); // g.ActiveId = 0;
3989
1.75k
}
3990
3991
void ImGui::SetHoveredID(ImGuiID id)
3992
1.59k
{
3993
1.59k
    ImGuiContext& g = *GImGui;
3994
1.59k
    g.HoveredId = id;
3995
1.59k
    g.HoveredIdAllowOverlap = false;
3996
1.59k
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3997
220
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3998
1.59k
}
3999
4000
ImGuiID ImGui::GetHoveredID()
4001
0
{
4002
0
    ImGuiContext& g = *GImGui;
4003
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4004
0
}
4005
4006
// This is called by ItemAdd().
4007
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
4008
void ImGui::KeepAliveID(ImGuiID id)
4009
257k
{
4010
257k
    ImGuiContext& g = *GImGui;
4011
257k
    if (g.ActiveId == id)
4012
2.07k
        g.ActiveIdIsAlive = id;
4013
257k
    if (g.ActiveIdPreviousFrame == id)
4014
1.97k
        g.ActiveIdPreviousFrameIsAlive = true;
4015
257k
}
4016
4017
void ImGui::MarkItemEdited(ImGuiID id)
4018
0
{
4019
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4020
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4021
0
    ImGuiContext& g = *GImGui;
4022
0
    if (g.LockMarkEdited > 0)
4023
0
        return;
4024
0
    if (g.ActiveId == id || g.ActiveId == 0)
4025
0
    {
4026
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4027
0
        g.ActiveIdHasBeenEditedBefore = true;
4028
0
    }
4029
4030
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4031
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4032
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4033
4034
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4035
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4036
0
}
4037
4038
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4039
1.61k
{
4040
    // An active popup disable hovering on other windows (apart from its own children)
4041
    // FIXME-OPT: This could be cached/stored within the window.
4042
1.61k
    ImGuiContext& g = *GImGui;
4043
1.61k
    if (g.NavWindow)
4044
1.05k
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4045
1.05k
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4046
0
            {
4047
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4048
                // NB: The 'else' is important because Modal windows are also Popups.
4049
0
                bool want_inhibit = false;
4050
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4051
0
                    want_inhibit = true;
4052
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4053
0
                    want_inhibit = true;
4054
4055
                // Inhibit hover unless the window is within the stack of our modal/popup
4056
0
                if (want_inhibit)
4057
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4058
0
                        return false;
4059
0
            }
4060
4061
    // Filter by viewport
4062
1.61k
    if (window->Viewport != g.MouseViewport)
4063
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4064
0
            return false;
4065
4066
1.61k
    return true;
4067
1.61k
}
4068
4069
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4070
0
{
4071
0
    ImGuiContext& g = *GImGui;
4072
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4073
0
        return g.Style.HoverDelayNormal;
4074
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4075
0
        return g.Style.HoverDelayShort;
4076
0
    return 0.0f;
4077
0
}
4078
4079
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4080
0
{
4081
    // Allow instance flags to override shared flags
4082
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4083
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4084
0
    return user_flags | shared_flags;
4085
0
}
4086
4087
// This is roughly matching the behavior of internal-facing ItemHoverable()
4088
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4089
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4090
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4091
0
{
4092
0
    ImGuiContext& g = *GImGui;
4093
0
    ImGuiWindow* window = g.CurrentWindow;
4094
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4095
4096
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4097
0
    {
4098
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4099
0
            return false;
4100
0
        if (!IsItemFocused())
4101
0
            return false;
4102
4103
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4104
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4105
0
    }
4106
0
    else
4107
0
    {
4108
        // Test for bounding box overlap, as updated as ItemAdd()
4109
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4110
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4111
0
            return false;
4112
4113
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4114
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4115
4116
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4117
4118
        // Done with rectangle culling so we can perform heavier checks now
4119
        // Test if we are hovering the right window (our window could be behind another window)
4120
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4121
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4122
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4123
        // the test that has been running for a long while.
4124
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4125
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4126
0
                return false;
4127
4128
        // Test if another item is active (e.g. being dragged)
4129
0
        const ImGuiID id = g.LastItemData.ID;
4130
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4131
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4132
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4133
0
                    return false;
4134
4135
        // Test if interactions on this window are blocked by an active popup or modal.
4136
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4137
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4138
0
            return false;
4139
4140
        // Test if the item is disabled
4141
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4142
0
            return false;
4143
4144
        // Special handling for calling after Begin() which represent the title bar or tab.
4145
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4146
        // will never be overwritten so we need to detect the case.
4147
0
        if (id == window->MoveId && window->WriteAccessed)
4148
0
            return false;
4149
4150
        // Test if using AllowOverlap and overlapped
4151
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4152
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4153
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4154
0
                    return false;
4155
0
    }
4156
4157
    // Handle hover delay
4158
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4159
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4160
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4161
0
    {
4162
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4163
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4164
0
            g.HoverItemDelayTimer = 0.0f;
4165
0
        g.HoverItemDelayId = hover_delay_id;
4166
4167
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4168
        // but once unlocked on a given item we also moving.
4169
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4170
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4171
0
            return false;
4172
4173
0
        if (g.HoverItemDelayTimer < delay)
4174
0
            return false;
4175
0
    }
4176
4177
0
    return true;
4178
0
}
4179
4180
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4181
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4182
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4183
// If you used this in your legacy/custom widgets code:
4184
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4185
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4186
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4187
210k
{
4188
210k
    ImGuiContext& g = *GImGui;
4189
210k
    ImGuiWindow* window = g.CurrentWindow;
4190
210k
    if (g.HoveredWindow != window)
4191
204k
        return false;
4192
6.28k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4193
4.43k
        return false;
4194
4195
1.84k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4196
2
        return false;
4197
1.84k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4198
255
        return false;
4199
4200
    // Done with rectangle culling so we can perform heavier checks now.
4201
1.59k
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4202
0
    {
4203
0
        g.HoveredIdDisabled = true;
4204
0
        return false;
4205
0
    }
4206
4207
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4208
    // hover test in widgets code. We could also decide to split this function is two.
4209
1.59k
    if (id != 0)
4210
1.59k
    {
4211
        // Drag source doesn't report as hovered
4212
1.59k
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4213
0
            return false;
4214
4215
1.59k
        SetHoveredID(id);
4216
4217
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4218
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4219
1.59k
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4220
0
        {
4221
0
            g.HoveredIdAllowOverlap = true;
4222
0
            if (g.HoveredIdPreviousFrame != id)
4223
0
                return false;
4224
0
        }
4225
1.59k
    }
4226
4227
    // When disabled we'll return false but still set HoveredId
4228
1.59k
    if (item_flags & ImGuiItemFlags_Disabled)
4229
0
    {
4230
        // Release active id if turning disabled
4231
0
        if (g.ActiveId == id && id != 0)
4232
0
            ClearActiveID();
4233
0
        g.HoveredIdDisabled = true;
4234
0
        return false;
4235
0
    }
4236
4237
1.59k
    if (id != 0)
4238
1.59k
    {
4239
        // [DEBUG] Item Picker tool!
4240
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4241
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4242
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4243
1.59k
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4244
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4245
1.59k
        if (g.DebugItemPickerBreakId == id)
4246
0
            IM_DEBUG_BREAK();
4247
1.59k
    }
4248
4249
1.59k
    if (g.NavDisableMouseHover)
4250
141
        return false;
4251
4252
1.45k
    return true;
4253
1.59k
}
4254
4255
// FIXME: This is inlined/duplicated in ItemAdd()
4256
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4257
0
{
4258
0
    ImGuiContext& g = *GImGui;
4259
0
    ImGuiWindow* window = g.CurrentWindow;
4260
0
    if (!bb.Overlaps(window->ClipRect))
4261
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4262
0
            if (!g.LogEnabled)
4263
0
                return true;
4264
0
    return false;
4265
0
}
4266
4267
// This is also inlined in ItemAdd()
4268
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4269
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4270
188k
{
4271
188k
    ImGuiContext& g = *GImGui;
4272
188k
    g.LastItemData.ID = item_id;
4273
188k
    g.LastItemData.InFlags = in_flags;
4274
188k
    g.LastItemData.StatusFlags = item_flags;
4275
188k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4276
188k
}
4277
4278
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4279
0
{
4280
0
    if (wrap_pos_x < 0.0f)
4281
0
        return 0.0f;
4282
4283
0
    ImGuiContext& g = *GImGui;
4284
0
    ImGuiWindow* window = g.CurrentWindow;
4285
0
    if (wrap_pos_x == 0.0f)
4286
0
    {
4287
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4288
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4289
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4290
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4291
        //else
4292
0
        wrap_pos_x = window->WorkRect.Max.x;
4293
0
    }
4294
0
    else if (wrap_pos_x > 0.0f)
4295
0
    {
4296
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4297
0
    }
4298
4299
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4300
0
}
4301
4302
// IM_ALLOC() == ImGui::MemAlloc()
4303
void* ImGui::MemAlloc(size_t size)
4304
1.24k
{
4305
1.24k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4306
1.24k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4307
1.24k
    if (ImGuiContext* ctx = GImGui)
4308
1.24k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4309
1.24k
#endif
4310
1.24k
    return ptr;
4311
1.24k
}
4312
4313
// IM_FREE() == ImGui::MemFree()
4314
void ImGui::MemFree(void* ptr)
4315
1.19k
{
4316
1.19k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4317
1.19k
    if (ptr != NULL)
4318
1.18k
        if (ImGuiContext* ctx = GImGui)
4319
1.18k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4320
1.19k
#endif
4321
1.19k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4322
1.19k
}
4323
4324
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4325
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4326
2.43k
{
4327
2.43k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4328
2.43k
    IM_UNUSED(ptr);
4329
2.43k
    if (entry->FrameCount != frame_count)
4330
46
    {
4331
46
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4332
46
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4333
46
        entry->FrameCount = frame_count;
4334
46
        entry->AllocCount = entry->FreeCount = 0;
4335
46
    }
4336
2.43k
    if (size != (size_t)-1)
4337
1.24k
    {
4338
1.24k
        entry->AllocCount++;
4339
1.24k
        info->TotalAllocCount++;
4340
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4341
1.24k
    }
4342
1.18k
    else
4343
1.18k
    {
4344
1.18k
        entry->FreeCount++;
4345
1.18k
        info->TotalFreeCount++;
4346
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4347
1.18k
    }
4348
2.43k
}
4349
4350
const char* ImGui::GetClipboardText()
4351
0
{
4352
0
    ImGuiContext& g = *GImGui;
4353
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4354
0
}
4355
4356
void ImGui::SetClipboardText(const char* text)
4357
0
{
4358
0
    ImGuiContext& g = *GImGui;
4359
0
    if (g.IO.SetClipboardTextFn)
4360
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4361
0
}
4362
4363
const char* ImGui::GetVersion()
4364
0
{
4365
0
    return IMGUI_VERSION;
4366
0
}
4367
4368
ImGuiIO& ImGui::GetIO()
4369
205k
{
4370
205k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4371
205k
    return GImGui->IO;
4372
205k
}
4373
4374
ImGuiPlatformIO& ImGui::GetPlatformIO()
4375
0
{
4376
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4377
0
    return GImGui->PlatformIO;
4378
0
}
4379
4380
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4381
ImDrawData* ImGui::GetDrawData()
4382
69.6k
{
4383
69.6k
    ImGuiContext& g = *GImGui;
4384
69.6k
    ImGuiViewportP* viewport = g.Viewports[0];
4385
69.6k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4386
69.6k
}
4387
4388
double ImGui::GetTime()
4389
11
{
4390
11
    return GImGui->Time;
4391
11
}
4392
4393
int ImGui::GetFrameCount()
4394
0
{
4395
0
    return GImGui->FrameCount;
4396
0
}
4397
4398
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4399
0
{
4400
    // Create the draw list on demand, because they are not frequently used for all viewports
4401
0
    ImGuiContext& g = *GImGui;
4402
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4403
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4404
0
    if (draw_list == NULL)
4405
0
    {
4406
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4407
0
        draw_list->_OwnerName = drawlist_name;
4408
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4409
0
    }
4410
4411
    // Our ImDrawList system requires that there is always a command
4412
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4413
0
    {
4414
0
        draw_list->_ResetForNewFrame();
4415
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4416
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4417
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4418
0
    }
4419
0
    return draw_list;
4420
0
}
4421
4422
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4423
0
{
4424
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4425
0
}
4426
4427
ImDrawList* ImGui::GetBackgroundDrawList()
4428
0
{
4429
0
    ImGuiContext& g = *GImGui;
4430
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4431
0
}
4432
4433
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4434
0
{
4435
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4436
0
}
4437
4438
ImDrawList* ImGui::GetForegroundDrawList()
4439
0
{
4440
0
    ImGuiContext& g = *GImGui;
4441
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4442
0
}
4443
4444
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4445
0
{
4446
0
    return &GImGui->DrawListSharedData;
4447
0
}
4448
4449
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4450
242
{
4451
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4452
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4453
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4454
242
    ImGuiContext& g = *GImGui;
4455
242
    FocusWindow(window);
4456
242
    SetActiveID(window->MoveId, window);
4457
242
    g.NavDisableHighlight = true;
4458
242
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4459
242
    g.ActiveIdNoClearOnFocusLoss = true;
4460
242
    SetActiveIdUsingAllKeyboardKeys();
4461
4462
242
    bool can_move_window = true;
4463
242
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4464
3
        can_move_window = false;
4465
242
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4466
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4467
0
            can_move_window = false;
4468
242
    if (can_move_window)
4469
239
        g.MovingWindow = window;
4470
242
}
4471
4472
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4473
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4474
99
{
4475
99
    ImGuiContext& g = *GImGui;
4476
99
    bool can_undock_node = false;
4477
99
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4478
0
    {
4479
        // Can undock if:
4480
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4481
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4482
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4483
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4484
0
            can_undock_node = true;
4485
0
    }
4486
4487
99
    const bool clicked = IsMouseClicked(0);
4488
99
    const bool dragging = IsMouseDragging(0);
4489
99
    if (can_undock_node && dragging)
4490
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4491
99
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4492
99
        StartMouseMovingWindow(window);
4493
99
}
4494
4495
// Handle mouse moving window
4496
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4497
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4498
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4499
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4500
void ImGui::UpdateMouseMovingWindowNewFrame()
4501
69.6k
{
4502
69.6k
    ImGuiContext& g = *GImGui;
4503
69.6k
    if (g.MovingWindow != NULL)
4504
920
    {
4505
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4506
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4507
920
        KeepAliveID(g.ActiveId);
4508
920
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4509
920
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4510
4511
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4512
920
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4513
920
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4514
681
        {
4515
681
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4516
681
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4517
223
            {
4518
223
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4519
223
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4520
0
                {
4521
0
                    moving_window->Viewport->Pos = pos;
4522
0
                    moving_window->Viewport->UpdateWorkRect();
4523
0
                }
4524
223
            }
4525
681
            FocusWindow(g.MovingWindow);
4526
681
        }
4527
239
        else
4528
239
        {
4529
239
            if (!window_disappared)
4530
239
            {
4531
                // Try to merge the window back into the main viewport.
4532
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4533
239
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4534
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4535
4536
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4537
239
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4538
239
                    g.MouseViewport = moving_window->Viewport;
4539
4540
                // Clear the NoInput window flag set by the Viewport system
4541
239
                if (moving_window->Viewport)
4542
239
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4543
239
            }
4544
4545
239
            g.MovingWindow = NULL;
4546
239
            ClearActiveID();
4547
239
        }
4548
920
    }
4549
68.7k
    else
4550
68.7k
    {
4551
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4552
68.7k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4553
8
        {
4554
8
            KeepAliveID(g.ActiveId);
4555
8
            if (!g.IO.MouseDown[0])
4556
3
                ClearActiveID();
4557
8
        }
4558
68.7k
    }
4559
69.6k
}
4560
4561
// Initiate moving window when clicking on empty space or title bar.
4562
// Handle left-click and right-click focus.
4563
void ImGui::UpdateMouseMovingWindowEndFrame()
4564
69.6k
{
4565
69.6k
    ImGuiContext& g = *GImGui;
4566
69.6k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4567
2.42k
        return;
4568
4569
    // Unless we just made a window/popup appear
4570
67.2k
    if (g.NavWindow && g.NavWindow->Appearing)
4571
8
        return;
4572
4573
    // Click on empty space to focus window and start moving
4574
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4575
67.2k
    if (g.IO.MouseClicked[0])
4576
1.09k
    {
4577
        // Handle the edge case of a popup being closed while clicking in its empty space.
4578
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4579
1.09k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4580
1.09k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4581
4582
1.09k
        if (root_window != NULL && !is_closed_popup)
4583
143
        {
4584
143
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4585
4586
            // Cancel moving if clicked outside of title bar
4587
143
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4588
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4589
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4590
0
                        g.MovingWindow = NULL;
4591
4592
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4593
143
            if (g.HoveredIdDisabled)
4594
0
                g.MovingWindow = NULL;
4595
143
        }
4596
952
        else if (root_window == NULL && g.NavWindow != NULL)
4597
176
        {
4598
            // Clicking on void disable focus
4599
176
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4600
176
        }
4601
1.09k
    }
4602
4603
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4604
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4605
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4606
67.2k
    if (g.IO.MouseClicked[1])
4607
133
    {
4608
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4609
        // This is where we can trim the popup stack.
4610
133
        ImGuiWindow* modal = GetTopMostPopupModal();
4611
133
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4612
133
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4613
133
    }
4614
67.2k
}
4615
4616
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4617
// Need to keep in sync with SetWindowPos()
4618
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4619
0
{
4620
0
    window->Pos += delta;
4621
0
    window->ClipRect.Translate(delta);
4622
0
    window->OuterRectClipped.Translate(delta);
4623
0
    window->InnerRect.Translate(delta);
4624
0
    window->DC.CursorPos += delta;
4625
0
    window->DC.CursorStartPos += delta;
4626
0
    window->DC.CursorMaxPos += delta;
4627
0
    window->DC.IdealMaxPos += delta;
4628
0
}
4629
4630
static void ScaleWindow(ImGuiWindow* window, float scale)
4631
0
{
4632
0
    ImVec2 origin = window->Viewport->Pos;
4633
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4634
0
    window->Size = ImTrunc(window->Size * scale);
4635
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4636
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4637
0
}
4638
4639
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4640
258k
{
4641
258k
    return (window->Active) && (!window->Hidden);
4642
258k
}
4643
4644
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4645
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4646
69.6k
{
4647
69.6k
    ImGuiContext& g = *GImGui;
4648
69.6k
    ImGuiIO& io = g.IO;
4649
69.6k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4650
4651
    // Find the window hovered by mouse:
4652
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4653
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4654
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4655
69.6k
    bool clear_hovered_windows = false;
4656
69.6k
    FindHoveredWindow();
4657
69.6k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4658
4659
    // Modal windows prevents mouse from hovering behind them.
4660
69.6k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4661
69.6k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4662
0
        clear_hovered_windows = true;
4663
4664
    // Disabled mouse?
4665
69.6k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4666
0
        clear_hovered_windows = true;
4667
4668
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4669
    // won't report hovering nor request capture even while dragging over our windows afterward.
4670
69.6k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4671
69.6k
    const bool has_open_modal = (modal_window != NULL);
4672
69.6k
    int mouse_earliest_down = -1;
4673
69.6k
    bool mouse_any_down = false;
4674
418k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4675
348k
    {
4676
348k
        if (io.MouseClicked[i])
4677
2.25k
        {
4678
2.25k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4679
2.25k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4680
2.25k
        }
4681
348k
        mouse_any_down |= io.MouseDown[i];
4682
348k
        if (io.MouseDown[i])
4683
17.9k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4684
12.8k
                mouse_earliest_down = i;
4685
348k
    }
4686
69.6k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4687
69.6k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4688
4689
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4690
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4691
69.6k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4692
69.6k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4693
8.93k
        clear_hovered_windows = true;
4694
4695
69.6k
    if (clear_hovered_windows)
4696
8.93k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4697
4698
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4699
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4700
69.6k
    if (g.WantCaptureMouseNextFrame != -1)
4701
0
    {
4702
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4703
0
    }
4704
69.6k
    else
4705
69.6k
    {
4706
69.6k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4707
69.6k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4708
69.6k
    }
4709
4710
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4711
69.6k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4712
69.6k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4713
38.6k
        io.WantCaptureKeyboard = true;
4714
69.6k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4715
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4716
4717
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4718
69.6k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4719
69.6k
}
4720
4721
void ImGui::NewFrame()
4722
69.6k
{
4723
69.6k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4724
69.6k
    ImGuiContext& g = *GImGui;
4725
4726
    // Remove pending delete hooks before frame start.
4727
    // This deferred removal avoid issues of removal while iterating the hook vector
4728
69.6k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4729
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4730
0
            g.Hooks.erase(&g.Hooks[n]);
4731
4732
69.6k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4733
4734
    // Check and assert for various common IO and Configuration mistakes
4735
69.6k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4736
69.6k
    ErrorCheckNewFrameSanityChecks();
4737
69.6k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4738
4739
    // Load settings on first frame, save settings when modified (after a delay)
4740
69.6k
    UpdateSettings();
4741
4742
69.6k
    g.Time += g.IO.DeltaTime;
4743
69.6k
    g.WithinFrameScope = true;
4744
69.6k
    g.FrameCount += 1;
4745
69.6k
    g.TooltipOverrideCount = 0;
4746
69.6k
    g.WindowsActiveCount = 0;
4747
69.6k
    g.MenusIdSubmittedThisFrame.resize(0);
4748
4749
    // Calculate frame-rate for the user, as a purely luxurious feature
4750
69.6k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4751
69.6k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4752
69.6k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4753
69.6k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4754
69.6k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4755
4756
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4757
69.6k
    g.InputEventsTrail.resize(0);
4758
69.6k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4759
4760
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4761
69.6k
    UpdateViewportsNewFrame();
4762
4763
    // Setup current font and draw list shared data
4764
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4765
69.6k
    g.IO.Fonts->Locked = true;
4766
69.6k
    SetCurrentFont(GetDefaultFont());
4767
69.6k
    IM_ASSERT(g.Font->IsLoaded());
4768
69.6k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4769
69.6k
    for (ImGuiViewportP* viewport : g.Viewports)
4770
69.6k
        virtual_space.Add(viewport->GetMainRect());
4771
69.6k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4772
69.6k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4773
69.6k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4774
69.6k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4775
69.6k
    if (g.Style.AntiAliasedLines)
4776
69.6k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4777
69.6k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4778
69.6k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4779
69.6k
    if (g.Style.AntiAliasedFill)
4780
69.6k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4781
69.6k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4782
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4783
4784
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4785
69.6k
    for (ImGuiViewportP* viewport : g.Viewports)
4786
69.6k
    {
4787
69.6k
        viewport->DrawData = NULL;
4788
69.6k
        viewport->DrawDataP.Valid = false;
4789
69.6k
    }
4790
4791
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4792
69.6k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4793
426
        KeepAliveID(g.DragDropPayload.SourceId);
4794
4795
    // Update HoveredId data
4796
69.6k
    if (!g.HoveredIdPreviousFrame)
4797
68.0k
        g.HoveredIdTimer = 0.0f;
4798
69.6k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4799
68.7k
        g.HoveredIdNotActiveTimer = 0.0f;
4800
69.6k
    if (g.HoveredId)
4801
1.59k
        g.HoveredIdTimer += g.IO.DeltaTime;
4802
69.6k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4803
880
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4804
69.6k
    g.HoveredIdPreviousFrame = g.HoveredId;
4805
69.6k
    g.HoveredId = 0;
4806
69.6k
    g.HoveredIdAllowOverlap = false;
4807
69.6k
    g.HoveredIdDisabled = false;
4808
4809
    // Clear ActiveID if the item is not alive anymore.
4810
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4811
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4812
69.6k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4813
0
    {
4814
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4815
0
        ClearActiveID();
4816
0
    }
4817
4818
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4819
69.6k
    if (g.ActiveId)
4820
1.67k
        g.ActiveIdTimer += g.IO.DeltaTime;
4821
69.6k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4822
69.6k
    g.ActiveIdPreviousFrame = g.ActiveId;
4823
69.6k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4824
69.6k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4825
69.6k
    g.ActiveIdIsAlive = 0;
4826
69.6k
    g.ActiveIdHasBeenEditedThisFrame = false;
4827
69.6k
    g.ActiveIdPreviousFrameIsAlive = false;
4828
69.6k
    g.ActiveIdIsJustActivated = false;
4829
69.6k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4830
0
        g.TempInputId = 0;
4831
69.6k
    if (g.ActiveId == 0)
4832
68.0k
    {
4833
68.0k
        g.ActiveIdUsingNavDirMask = 0x00;
4834
68.0k
        g.ActiveIdUsingAllKeyboardKeys = false;
4835
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4836
        g.ActiveIdUsingNavInputMask = 0x00;
4837
#endif
4838
68.0k
    }
4839
4840
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4841
    if (g.ActiveId == 0)
4842
        g.ActiveIdUsingNavInputMask = 0;
4843
    else if (g.ActiveIdUsingNavInputMask != 0)
4844
    {
4845
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4846
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4847
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4848
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4849
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4850
            IM_ASSERT(0); // Other values unsupported
4851
    }
4852
#endif
4853
4854
    // Record when we have been stationary as this state is preserved while over same item.
4855
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4856
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4857
69.6k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4858
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4859
69.6k
    else if (g.HoverItemDelayId == 0)
4860
69.6k
        g.HoverItemUnlockedStationaryId = 0;
4861
69.6k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4862
2.50k
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4863
67.1k
    else if (g.HoveredWindow == NULL)
4864
66.1k
        g.HoverWindowUnlockedStationaryId = 0;
4865
4866
    // Update hover delay for IsItemHovered() with delays and tooltips
4867
69.6k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4868
69.6k
    if (g.HoverItemDelayId != 0)
4869
0
    {
4870
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4871
0
        g.HoverItemDelayClearTimer = 0.0f;
4872
0
        g.HoverItemDelayId = 0;
4873
0
    }
4874
69.6k
    else if (g.HoverItemDelayTimer > 0.0f)
4875
0
    {
4876
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4877
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4878
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4879
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4880
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4881
0
    }
4882
4883
    // Drag and drop
4884
69.6k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4885
69.6k
    g.DragDropAcceptIdCurr = 0;
4886
69.6k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4887
69.6k
    g.DragDropWithinSource = false;
4888
69.6k
    g.DragDropWithinTarget = false;
4889
69.6k
    g.DragDropHoldJustPressedId = 0;
4890
4891
    // Close popups on focus lost (currently wip/opt-in)
4892
    //if (g.IO.AppFocusLost)
4893
    //    ClosePopupsExceptModals();
4894
4895
    // Update keyboard input state
4896
69.6k
    UpdateKeyboardInputs();
4897
4898
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4899
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4900
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4901
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4902
4903
    // Update gamepad/keyboard navigation
4904
69.6k
    NavUpdate();
4905
4906
    // Update mouse input state
4907
69.6k
    UpdateMouseInputs();
4908
4909
    // Undocking
4910
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4911
69.6k
    DockContextNewFrameUpdateUndocking(&g);
4912
4913
    // Find hovered window
4914
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4915
69.6k
    UpdateHoveredWindowAndCaptureFlags();
4916
4917
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4918
69.6k
    UpdateMouseMovingWindowNewFrame();
4919
4920
    // Background darkening/whitening
4921
69.6k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4922
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4923
69.6k
    else
4924
69.6k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4925
4926
69.6k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4927
69.6k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4928
4929
    // Platform IME data: reset for the frame
4930
69.6k
    g.PlatformImeDataPrev = g.PlatformImeData;
4931
69.6k
    g.PlatformImeData.WantVisible = false;
4932
4933
    // Mouse wheel scrolling, scale
4934
69.6k
    UpdateMouseWheel();
4935
4936
    // Mark all windows as not visible and compact unused memory.
4937
69.6k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4938
69.6k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4939
69.6k
    for (ImGuiWindow* window : g.Windows)
4940
209k
    {
4941
209k
        window->WasActive = window->Active;
4942
209k
        window->Active = false;
4943
209k
        window->WriteAccessed = false;
4944
209k
        window->BeginCountPreviousFrame = window->BeginCount;
4945
209k
        window->BeginCount = 0;
4946
4947
        // Garbage collect transient buffers of recently unused windows
4948
209k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4949
3
            GcCompactTransientWindowBuffers(window);
4950
209k
    }
4951
4952
    // Garbage collect transient buffers of recently unused tables
4953
69.6k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4954
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4955
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4956
69.6k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4957
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4958
0
            TableGcCompactTransientBuffers(&table_temp_data);
4959
69.6k
    if (g.GcCompactAll)
4960
0
        GcCompactTransientMiscBuffers();
4961
69.6k
    g.GcCompactAll = false;
4962
4963
    // Closing the focused window restore focus to the first active root window in descending z-order
4964
69.6k
    if (g.NavWindow && !g.NavWindow->WasActive)
4965
1
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4966
4967
    // No window should be open at the beginning of the frame.
4968
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4969
69.6k
    g.CurrentWindowStack.resize(0);
4970
69.6k
    g.BeginPopupStack.resize(0);
4971
69.6k
    g.ItemFlagsStack.resize(0);
4972
69.6k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4973
69.6k
    g.GroupStack.resize(0);
4974
4975
    // Docking
4976
69.6k
    DockContextNewFrameUpdateDocking(&g);
4977
4978
    // [DEBUG] Update debug features
4979
69.6k
    UpdateDebugToolItemPicker();
4980
69.6k
    UpdateDebugToolStackQueries();
4981
69.6k
    UpdateDebugToolFlashStyleColor();
4982
69.6k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4983
0
        g.DebugLocateId = 0;
4984
69.6k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
4985
0
    {
4986
0
        DebugLog("(Debug Log: Auto-disabled ImGuiDebugLogFlags_EventClipper after 2 frames)\n");
4987
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
4988
0
    }
4989
4990
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4991
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4992
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4993
69.6k
    g.WithinFrameScopeWithImplicitWindow = true;
4994
69.6k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4995
69.6k
    Begin("Debug##Default");
4996
69.6k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4997
4998
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4999
    // allowing to validate correct Begin/End behavior in user code.
5000
69.6k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5001
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5002
69.6k
    else
5003
69.6k
        g.DebugBeginReturnValueCullDepth = -1;
5004
5005
69.6k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5006
69.6k
}
5007
5008
// FIXME: Add a more explicit sort order in the window structure.
5009
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5010
0
{
5011
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5012
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5013
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5014
0
        return d;
5015
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5016
0
        return d;
5017
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5018
0
}
5019
5020
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5021
209k
{
5022
209k
    out_sorted_windows->push_back(window);
5023
209k
    if (window->Active)
5024
118k
    {
5025
118k
        int count = window->DC.ChildWindows.Size;
5026
118k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5027
167k
        for (int i = 0; i < count; i++)
5028
49.0k
        {
5029
49.0k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5030
49.0k
            if (child->Active)
5031
49.0k
                AddWindowToSortBuffer(out_sorted_windows, child);
5032
49.0k
        }
5033
118k
    }
5034
209k
}
5035
5036
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5037
92.8k
{
5038
92.8k
    ImGuiContext& g = *GImGui;
5039
92.8k
    ImGuiViewportP* viewport = window->Viewport;
5040
92.8k
    IM_ASSERT(viewport != NULL);
5041
92.8k
    g.IO.MetricsRenderWindows++;
5042
92.8k
    if (window->DrawList->_Splitter._Count > 1)
5043
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5044
92.8k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5045
92.8k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5046
49.0k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5047
23.1k
            AddWindowToDrawData(child, layer);
5048
92.8k
}
5049
5050
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5051
69.6k
{
5052
69.6k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5053
69.6k
}
5054
5055
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5056
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5057
69.6k
{
5058
69.6k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5059
69.6k
}
5060
5061
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5062
69.6k
{
5063
69.6k
    int n = builder->Layers[0]->Size;
5064
69.6k
    int full_size = n;
5065
139k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5066
69.6k
        full_size += builder->Layers[i]->Size;
5067
69.6k
    builder->Layers[0]->resize(full_size);
5068
139k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5069
69.6k
    {
5070
69.6k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5071
69.6k
        if (layer->empty())
5072
69.6k
            continue;
5073
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5074
0
        n += layer->Size;
5075
0
        layer->resize(0);
5076
0
    }
5077
69.6k
}
5078
5079
static void InitViewportDrawData(ImGuiViewportP* viewport)
5080
69.6k
{
5081
69.6k
    ImGuiIO& io = ImGui::GetIO();
5082
69.6k
    ImDrawData* draw_data = &viewport->DrawDataP;
5083
5084
69.6k
    viewport->DrawData = draw_data; // Make publicly accessible
5085
69.6k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5086
69.6k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5087
69.6k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5088
69.6k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5089
5090
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5091
    // and to allow applications/backends to easily skip rendering.
5092
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5093
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5094
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5095
69.6k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5096
5097
69.6k
    draw_data->Valid = true;
5098
69.6k
    draw_data->CmdListsCount = 0;
5099
69.6k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5100
69.6k
    draw_data->DisplayPos = viewport->Pos;
5101
69.6k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5102
69.6k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5103
69.6k
    draw_data->OwnerViewport = viewport;
5104
69.6k
}
5105
5106
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5107
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5108
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5109
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5110
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5111
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5112
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5113
376k
{
5114
376k
    ImGuiWindow* window = GetCurrentWindow();
5115
376k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5116
376k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5117
376k
}
5118
5119
void ImGui::PopClipRect()
5120
188k
{
5121
188k
    ImGuiWindow* window = GetCurrentWindow();
5122
188k
    window->DrawList->PopClipRect();
5123
188k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5124
188k
}
5125
5126
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5127
0
{
5128
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5129
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5130
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5131
0
    return window;
5132
0
}
5133
5134
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5135
0
{
5136
0
    if ((col & IM_COL32_A_MASK) == 0)
5137
0
        return;
5138
5139
0
    ImGuiViewportP* viewport = window->Viewport;
5140
0
    ImRect viewport_rect = viewport->GetMainRect();
5141
5142
    // Draw behind window by moving the draw command at the FRONT of the draw list
5143
0
    {
5144
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5145
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5146
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5147
0
        draw_list->ChannelsMerge();
5148
0
        if (draw_list->CmdBuffer.Size == 0)
5149
0
            draw_list->AddDrawCmd();
5150
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5151
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5152
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5153
0
        IM_ASSERT(cmd.ElemCount == 6);
5154
0
        draw_list->CmdBuffer.pop_back();
5155
0
        draw_list->CmdBuffer.push_front(cmd);
5156
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5157
0
        draw_list->PopClipRect();
5158
0
    }
5159
5160
    // Draw over sibling docking nodes in a same docking tree
5161
0
    if (window->RootWindow->DockIsActive)
5162
0
    {
5163
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5164
0
        draw_list->ChannelsMerge();
5165
0
        if (draw_list->CmdBuffer.Size == 0)
5166
0
            draw_list->AddDrawCmd();
5167
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5168
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5169
0
        draw_list->PopClipRect();
5170
0
    }
5171
0
}
5172
5173
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5174
0
{
5175
0
    ImGuiContext& g = *GImGui;
5176
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5177
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5178
0
    {
5179
0
        ImGuiWindow* window = g.Windows[i];
5180
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5181
0
            continue;
5182
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5183
0
            break;
5184
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5185
0
            bottom_most_visible_window = window;
5186
0
    }
5187
0
    return bottom_most_visible_window;
5188
0
}
5189
5190
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5191
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5192
static void ImGui::RenderDimmedBackgrounds()
5193
69.6k
{
5194
69.6k
    ImGuiContext& g = *GImGui;
5195
69.6k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5196
69.6k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5197
69.6k
        return;
5198
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5199
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5200
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5201
0
        return;
5202
5203
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5204
0
    if (dim_bg_for_modal)
5205
0
    {
5206
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5207
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5208
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5209
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5210
0
    }
5211
0
    else if (dim_bg_for_window_list)
5212
0
    {
5213
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5214
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5215
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5216
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5217
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5218
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5219
5220
        // Draw border around CTRL+Tab target window
5221
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5222
0
        ImGuiViewport* viewport = window->Viewport;
5223
0
        float distance = g.FontSize;
5224
0
        ImRect bb = window->Rect();
5225
0
        bb.Expand(distance);
5226
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5227
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5228
0
        window->DrawList->ChannelsMerge();
5229
0
        if (window->DrawList->CmdBuffer.Size == 0)
5230
0
            window->DrawList->AddDrawCmd();
5231
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5232
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5233
0
        window->DrawList->PopClipRect();
5234
0
    }
5235
5236
    // Draw dimming background on _other_ viewports than the ones our windows are in
5237
0
    for (ImGuiViewportP* viewport : g.Viewports)
5238
0
    {
5239
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5240
0
            continue;
5241
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5242
0
            continue;
5243
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5244
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5245
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5246
0
    }
5247
0
}
5248
5249
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5250
void ImGui::EndFrame()
5251
139k
{
5252
139k
    ImGuiContext& g = *GImGui;
5253
139k
    IM_ASSERT(g.Initialized);
5254
5255
    // Don't process EndFrame() multiple times.
5256
139k
    if (g.FrameCountEnded == g.FrameCount)
5257
69.6k
        return;
5258
69.6k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5259
5260
69.6k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5261
5262
69.6k
    ErrorCheckEndFrameSanityChecks();
5263
5264
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5265
69.6k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5266
69.6k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5267
0
    {
5268
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5269
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5270
0
        if (viewport == NULL)
5271
0
            viewport = GetMainViewport();
5272
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5273
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5274
        {
5275
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5276
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5277
            viewport->PlatformHandleRaw = NULL;
5278
        }
5279
        else
5280
#endif
5281
0
        {
5282
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5283
0
        }
5284
0
    }
5285
5286
    // Hide implicit/fallback "Debug" window if it hasn't been used
5287
69.6k
    g.WithinFrameScopeWithImplicitWindow = false;
5288
69.6k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5289
69.6k
        g.CurrentWindow->Active = false;
5290
69.6k
    End();
5291
5292
    // Update navigation: CTRL+Tab, wrap-around requests
5293
69.6k
    NavEndFrame();
5294
5295
    // Update docking
5296
69.6k
    DockContextEndFrame(&g);
5297
5298
69.6k
    SetCurrentViewport(NULL, NULL);
5299
5300
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5301
69.6k
    if (g.DragDropActive)
5302
660
    {
5303
660
        bool is_delivered = g.DragDropPayload.Delivery;
5304
660
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5305
660
        if (is_delivered || is_elapsed)
5306
117
            ClearDragDrop();
5307
660
    }
5308
5309
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5310
69.6k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5311
0
    {
5312
0
        g.DragDropWithinSource = true;
5313
0
        SetTooltip("...");
5314
0
        g.DragDropWithinSource = false;
5315
0
    }
5316
5317
    // End frame
5318
69.6k
    g.WithinFrameScope = false;
5319
69.6k
    g.FrameCountEnded = g.FrameCount;
5320
5321
    // Initiate moving window + handle left-click and right-click focus
5322
69.6k
    UpdateMouseMovingWindowEndFrame();
5323
5324
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5325
69.6k
    UpdateViewportsEndFrame();
5326
5327
    // Sort the window list so that all child windows are after their parent
5328
    // We cannot do that on FocusWindow() because children may not exist yet
5329
69.6k
    g.WindowsTempSortBuffer.resize(0);
5330
69.6k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5331
69.6k
    for (ImGuiWindow* window : g.Windows)
5332
209k
    {
5333
209k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5334
49.0k
            continue;
5335
159k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5336
159k
    }
5337
5338
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5339
69.6k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5340
69.6k
    g.Windows.swap(g.WindowsTempSortBuffer);
5341
69.6k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5342
5343
    // Unlock font atlas
5344
69.6k
    g.IO.Fonts->Locked = false;
5345
5346
    // Clear Input data for next frame
5347
69.6k
    g.IO.MousePosPrev = g.IO.MousePos;
5348
69.6k
    g.IO.AppFocusLost = false;
5349
69.6k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5350
69.6k
    g.IO.InputQueueCharacters.resize(0);
5351
5352
69.6k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5353
69.6k
}
5354
5355
// Prepare the data for rendering so you can call GetDrawData()
5356
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5357
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5358
void ImGui::Render()
5359
69.6k
{
5360
69.6k
    ImGuiContext& g = *GImGui;
5361
69.6k
    IM_ASSERT(g.Initialized);
5362
5363
69.6k
    if (g.FrameCountEnded != g.FrameCount)
5364
69.6k
        EndFrame();
5365
69.6k
    if (g.FrameCountRendered == g.FrameCount)
5366
0
        return;
5367
69.6k
    g.FrameCountRendered = g.FrameCount;
5368
5369
69.6k
    g.IO.MetricsRenderWindows = 0;
5370
69.6k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5371
5372
    // Add background ImDrawList (for each active viewport)
5373
69.6k
    for (ImGuiViewportP* viewport : g.Viewports)
5374
69.6k
    {
5375
69.6k
        InitViewportDrawData(viewport);
5376
69.6k
        if (viewport->BgFgDrawLists[0] != NULL)
5377
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5378
69.6k
    }
5379
5380
    // Draw modal/window whitening backgrounds
5381
69.6k
    RenderDimmedBackgrounds();
5382
5383
    // Add ImDrawList to render
5384
69.6k
    ImGuiWindow* windows_to_render_top_most[2];
5385
69.6k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5386
69.6k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5387
69.6k
    for (ImGuiWindow* window : g.Windows)
5388
209k
    {
5389
209k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5390
209k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5391
69.6k
            AddRootWindowToDrawData(window);
5392
209k
    }
5393
209k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5394
139k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5395
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5396
5397
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5398
69.6k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5399
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5400
5401
    // Setup ImDrawData structures for end-user
5402
69.6k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5403
69.6k
    for (ImGuiViewportP* viewport : g.Viewports)
5404
69.6k
    {
5405
69.6k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5406
5407
        // Add foreground ImDrawList (for each active viewport)
5408
69.6k
        if (viewport->BgFgDrawLists[1] != NULL)
5409
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5410
5411
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5412
69.6k
        ImDrawData* draw_data = &viewport->DrawDataP;
5413
69.6k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5414
69.6k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5415
92.6k
            draw_list->_PopUnusedDrawCmd();
5416
5417
69.6k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5418
69.6k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5419
69.6k
    }
5420
5421
69.6k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5422
69.6k
}
5423
5424
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5425
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5426
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5427
139k
{
5428
139k
    ImGuiContext& g = *GImGui;
5429
5430
139k
    const char* text_display_end;
5431
139k
    if (hide_text_after_double_hash)
5432
139k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5433
0
    else
5434
0
        text_display_end = text_end;
5435
5436
139k
    ImFont* font = g.Font;
5437
139k
    const float font_size = g.FontSize;
5438
139k
    if (text == text_display_end)
5439
0
        return ImVec2(0.0f, font_size);
5440
139k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5441
5442
    // Round
5443
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5444
    // FIXME: Investigate using ceilf or e.g.
5445
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5446
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5447
139k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5448
5449
139k
    return text_size;
5450
139k
}
5451
5452
// Find window given position, search front-to-back
5453
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5454
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5455
// called, aka before the next Begin(). Moving window isn't affected.
5456
static void FindHoveredWindow()
5457
69.6k
{
5458
69.6k
    ImGuiContext& g = *GImGui;
5459
5460
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5461
69.6k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5462
69.6k
    if (g.MovingWindow)
5463
920
        g.MovingWindow->Viewport = g.MouseViewport;
5464
5465
69.6k
    ImGuiWindow* hovered_window = NULL;
5466
69.6k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5467
69.6k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5468
920
        hovered_window = g.MovingWindow;
5469
5470
69.6k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5471
69.6k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5472
273k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5473
206k
    {
5474
206k
        ImGuiWindow* window = g.Windows[i];
5475
206k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5476
206k
        if (!window->Active || window->Hidden)
5477
113k
            continue;
5478
92.8k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5479
0
            continue;
5480
92.8k
        IM_ASSERT(window->Viewport);
5481
92.8k
        if (window->Viewport != g.MouseViewport)
5482
0
            continue;
5483
5484
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5485
92.8k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5486
92.8k
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5487
89.2k
            continue;
5488
5489
        // Support for one rectangular hole in any given window
5490
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5491
3.55k
        if (window->HitTestHoleSize.x != 0)
5492
0
        {
5493
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5494
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5495
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5496
0
                continue;
5497
0
        }
5498
5499
3.55k
        if (hovered_window == NULL)
5500
2.85k
            hovered_window = window;
5501
3.55k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5502
3.55k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5503
2.85k
            hovered_window_ignoring_moving_window = window;
5504
3.55k
        if (hovered_window && hovered_window_ignoring_moving_window)
5505
2.85k
            break;
5506
3.55k
    }
5507
5508
69.6k
    g.HoveredWindow = hovered_window;
5509
69.6k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5510
5511
69.6k
    if (g.MovingWindow)
5512
920
        g.MovingWindow->Viewport = moving_window_viewport;
5513
69.6k
}
5514
5515
bool ImGui::IsItemActive()
5516
131k
{
5517
131k
    ImGuiContext& g = *GImGui;
5518
131k
    if (g.ActiveId)
5519
2.82k
        return g.ActiveId == g.LastItemData.ID;
5520
128k
    return false;
5521
131k
}
5522
5523
bool ImGui::IsItemActivated()
5524
0
{
5525
0
    ImGuiContext& g = *GImGui;
5526
0
    if (g.ActiveId)
5527
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5528
0
            return true;
5529
0
    return false;
5530
0
}
5531
5532
bool ImGui::IsItemDeactivated()
5533
0
{
5534
0
    ImGuiContext& g = *GImGui;
5535
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5536
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5537
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5538
0
}
5539
5540
bool ImGui::IsItemDeactivatedAfterEdit()
5541
0
{
5542
0
    ImGuiContext& g = *GImGui;
5543
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5544
0
}
5545
5546
// == GetItemID() == GetFocusID()
5547
bool ImGui::IsItemFocused()
5548
0
{
5549
0
    ImGuiContext& g = *GImGui;
5550
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5551
0
        return false;
5552
5553
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5554
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5555
0
    ImGuiWindow* window = g.CurrentWindow;
5556
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5557
0
        return false;
5558
5559
0
    return true;
5560
0
}
5561
5562
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5563
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5564
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5565
0
{
5566
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5567
0
}
5568
5569
bool ImGui::IsItemToggledOpen()
5570
0
{
5571
0
    ImGuiContext& g = *GImGui;
5572
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5573
0
}
5574
5575
bool ImGui::IsItemToggledSelection()
5576
0
{
5577
0
    ImGuiContext& g = *GImGui;
5578
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5579
0
}
5580
5581
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5582
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5583
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5584
bool ImGui::IsAnyItemHovered()
5585
0
{
5586
0
    ImGuiContext& g = *GImGui;
5587
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5588
0
}
5589
5590
bool ImGui::IsAnyItemActive()
5591
0
{
5592
0
    ImGuiContext& g = *GImGui;
5593
0
    return g.ActiveId != 0;
5594
0
}
5595
5596
bool ImGui::IsAnyItemFocused()
5597
0
{
5598
0
    ImGuiContext& g = *GImGui;
5599
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5600
0
}
5601
5602
bool ImGui::IsItemVisible()
5603
0
{
5604
0
    ImGuiContext& g = *GImGui;
5605
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5606
0
}
5607
5608
bool ImGui::IsItemEdited()
5609
0
{
5610
0
    ImGuiContext& g = *GImGui;
5611
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5612
0
}
5613
5614
// Allow next item to be overlapped by subsequent items.
5615
// This works by requiring HoveredId to match for two subsequent frames,
5616
// so if a following items overwrite it our interactions will naturally be disabled.
5617
void ImGui::SetNextItemAllowOverlap()
5618
0
{
5619
0
    ImGuiContext& g = *GImGui;
5620
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5621
0
}
5622
5623
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5624
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5625
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5626
void ImGui::SetItemAllowOverlap()
5627
{
5628
    ImGuiContext& g = *GImGui;
5629
    ImGuiID id = g.LastItemData.ID;
5630
    if (g.HoveredId == id)
5631
        g.HoveredIdAllowOverlap = true;
5632
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5633
        g.ActiveIdAllowOverlap = true;
5634
}
5635
#endif
5636
5637
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5638
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5639
836
{
5640
836
    ImGuiContext& g = *GImGui;
5641
836
    IM_ASSERT(g.ActiveId != 0);
5642
836
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5643
836
    g.ActiveIdUsingAllKeyboardKeys = true;
5644
836
    NavMoveRequestCancel();
5645
836
}
5646
5647
ImGuiID ImGui::GetItemID()
5648
0
{
5649
0
    ImGuiContext& g = *GImGui;
5650
0
    return g.LastItemData.ID;
5651
0
}
5652
5653
ImVec2 ImGui::GetItemRectMin()
5654
0
{
5655
0
    ImGuiContext& g = *GImGui;
5656
0
    return g.LastItemData.Rect.Min;
5657
0
}
5658
5659
ImVec2 ImGui::GetItemRectMax()
5660
0
{
5661
0
    ImGuiContext& g = *GImGui;
5662
0
    return g.LastItemData.Rect.Max;
5663
0
}
5664
5665
ImVec2 ImGui::GetItemRectSize()
5666
0
{
5667
0
    ImGuiContext& g = *GImGui;
5668
0
    return g.LastItemData.Rect.GetSize();
5669
0
}
5670
5671
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5672
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'.
5673
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5674
49.0k
{
5675
49.0k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5676
49.0k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5677
49.0k
}
5678
5679
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5680
0
{
5681
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5682
0
}
5683
5684
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5685
49.0k
{
5686
49.0k
    ImGuiContext& g = *GImGui;
5687
49.0k
    ImGuiWindow* parent_window = g.CurrentWindow;
5688
49.0k
    IM_ASSERT(id != 0);
5689
5690
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5691
49.0k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5692
49.0k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5693
49.0k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5694
49.0k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5695
49.0k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5696
0
    {
5697
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5698
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5699
0
    }
5700
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5701
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5702
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5703
#endif
5704
49.0k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5705
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5706
49.0k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5707
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5708
5709
    // Set window flags
5710
49.0k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5711
49.0k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5712
49.0k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5713
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5714
49.0k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5715
49.0k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5716
5717
    // Special framed style
5718
49.0k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5719
0
    {
5720
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5721
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5722
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5723
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5724
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5725
0
        window_flags |= ImGuiWindowFlags_NoMove;
5726
0
    }
5727
5728
    // Forward child flags
5729
49.0k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5730
49.0k
    g.NextWindowData.ChildFlags = child_flags;
5731
5732
    // Forward size
5733
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5734
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5735
49.0k
    const ImVec2 size_avail = GetContentRegionAvail();
5736
49.0k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5737
49.0k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5738
49.0k
    SetNextWindowSize(size);
5739
5740
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5741
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5742
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5743
49.0k
    const char* temp_window_name;
5744
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5745
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5746
    else*/
5747
49.0k
    if (name)
5748
49.0k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5749
0
    else
5750
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5751
5752
    // Set style
5753
49.0k
    const float backup_border_size = g.Style.ChildBorderSize;
5754
49.0k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5755
22.7k
        g.Style.ChildBorderSize = 0.0f;
5756
5757
    // Begin into window
5758
49.0k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5759
5760
    // Restore style
5761
49.0k
    g.Style.ChildBorderSize = backup_border_size;
5762
49.0k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5763
0
    {
5764
0
        PopStyleVar(3);
5765
0
        PopStyleColor();
5766
0
    }
5767
5768
49.0k
    ImGuiWindow* child_window = g.CurrentWindow;
5769
49.0k
    child_window->ChildId = id;
5770
5771
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5772
    // While this is not really documented/defined, it seems that the expected thing to do.
5773
49.0k
    if (child_window->BeginCount == 1)
5774
49.0k
        parent_window->DC.CursorPos = child_window->Pos;
5775
5776
    // Process navigation-in immediately so NavInit can run on first frame
5777
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5778
49.0k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5779
49.0k
    if (g.ActiveId == temp_id_for_activation)
5780
35
        ClearActiveID();
5781
49.0k
    if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5782
39
    {
5783
39
        FocusWindow(child_window);
5784
39
        NavInitWindow(child_window, false);
5785
39
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5786
39
        g.ActiveIdSource = g.NavInputSource;
5787
39
    }
5788
49.0k
    return ret;
5789
49.0k
}
5790
5791
void ImGui::EndChild()
5792
49.0k
{
5793
49.0k
    ImGuiContext& g = *GImGui;
5794
49.0k
    ImGuiWindow* child_window = g.CurrentWindow;
5795
5796
49.0k
    IM_ASSERT(g.WithinEndChild == false);
5797
49.0k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5798
5799
49.0k
    g.WithinEndChild = true;
5800
49.0k
    ImVec2 child_size = child_window->Size;
5801
49.0k
    End();
5802
49.0k
    if (child_window->BeginCount == 1)
5803
49.0k
    {
5804
49.0k
        ImGuiWindow* parent_window = g.CurrentWindow;
5805
49.0k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5806
49.0k
        ItemSize(child_size);
5807
49.0k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5808
45.6k
        {
5809
45.6k
            ItemAdd(bb, child_window->ChildId);
5810
45.6k
            RenderNavHighlight(bb, child_window->ChildId);
5811
5812
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5813
45.6k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5814
29.2k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5815
45.6k
        }
5816
3.43k
        else
5817
3.43k
        {
5818
            // Not navigable into
5819
3.43k
            ItemAdd(bb, 0);
5820
5821
            // But when flattened we directly reach items, adjust active layer mask accordingly
5822
3.43k
            if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5823
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5824
3.43k
        }
5825
49.0k
        if (g.HoveredWindow == child_window)
5826
22
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5827
49.0k
    }
5828
49.0k
    g.WithinEndChild = false;
5829
49.0k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5830
49.0k
}
5831
5832
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5833
36
{
5834
36
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5835
36
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5836
36
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5837
36
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5838
36
}
5839
5840
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5841
188k
{
5842
188k
    ImGuiContext& g = *GImGui;
5843
188k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5844
188k
}
5845
5846
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5847
188k
{
5848
188k
    ImGuiID id = ImHashStr(name);
5849
188k
    return FindWindowByID(id);
5850
188k
}
5851
5852
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5853
0
{
5854
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5855
0
    window->ViewportPos = main_viewport->Pos;
5856
0
    if (settings->ViewportId)
5857
0
    {
5858
0
        window->ViewportId = settings->ViewportId;
5859
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5860
0
    }
5861
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5862
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5863
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5864
0
    window->Collapsed = settings->Collapsed;
5865
0
    window->DockId = settings->DockId;
5866
0
    window->DockOrder = settings->DockOrder;
5867
0
}
5868
5869
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5870
188k
{
5871
188k
    ImGuiContext& g = *GImGui;
5872
5873
188k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5874
188k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5875
188k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5876
2
    {
5877
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5878
2
        g.WindowsFocusOrder.push_back(window);
5879
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5880
2
    }
5881
188k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5882
0
    {
5883
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5884
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5885
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5886
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5887
0
        window->FocusOrder = -1;
5888
0
    }
5889
188k
    window->IsExplicitChild = new_is_explicit_child;
5890
188k
}
5891
5892
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5893
3
{
5894
    // Initial window state with e.g. default/arbitrary window position
5895
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5896
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5897
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5898
3
    window->Size = window->SizeFull = ImVec2(0, 0);
5899
3
    window->ViewportPos = main_viewport->Pos;
5900
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5901
5902
3
    if (settings != NULL)
5903
0
    {
5904
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5905
0
        ApplyWindowSettings(window, settings);
5906
0
    }
5907
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5908
5909
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5910
0
    {
5911
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5912
0
        window->AutoFitOnlyGrows = false;
5913
0
    }
5914
3
    else
5915
3
    {
5916
3
        if (window->Size.x <= 0.0f)
5917
3
            window->AutoFitFramesX = 2;
5918
3
        if (window->Size.y <= 0.0f)
5919
3
            window->AutoFitFramesY = 2;
5920
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5921
3
    }
5922
3
}
5923
5924
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5925
3
{
5926
    // Create window the first time
5927
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5928
3
    ImGuiContext& g = *GImGui;
5929
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5930
3
    window->Flags = flags;
5931
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5932
5933
3
    ImGuiWindowSettings* settings = NULL;
5934
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5935
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5936
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5937
5938
3
    InitOrLoadWindowSettings(window, settings);
5939
5940
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5941
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5942
3
    else
5943
3
        g.Windows.push_back(window);
5944
5945
3
    return window;
5946
3
}
5947
5948
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5949
0
{
5950
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5951
0
}
5952
5953
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5954
418k
{
5955
418k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5956
418k
}
5957
5958
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5959
565k
{
5960
    // Popups, menus and childs bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5961
    // FIXME: the if/else could probably be removed, "reduce artifacts" section for all windows.
5962
565k
    ImGuiContext& g = *GImGui;
5963
565k
    ImVec2 size_min;
5964
565k
    if (window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_ChildWindow))
5965
147k
    {
5966
147k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5967
147k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5968
147k
    }
5969
418k
    else
5970
418k
    {
5971
418k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5972
418k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5973
418k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5974
418k
        size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
5975
418k
    }
5976
565k
    return size_min;
5977
565k
}
5978
5979
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5980
376k
{
5981
376k
    ImGuiContext& g = *GImGui;
5982
376k
    ImVec2 new_size = size_desired;
5983
376k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5984
0
    {
5985
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
5986
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5987
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5988
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5989
0
        if (g.NextWindowData.SizeCallback)
5990
0
        {
5991
0
            ImGuiSizeCallbackData data;
5992
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5993
0
            data.Pos = window->Pos;
5994
0
            data.CurrentSize = window->SizeFull;
5995
0
            data.DesiredSize = new_size;
5996
0
            g.NextWindowData.SizeCallback(&data);
5997
0
            new_size = data.DesiredSize;
5998
0
        }
5999
0
        new_size.x = IM_TRUNC(new_size.x);
6000
0
        new_size.y = IM_TRUNC(new_size.y);
6001
0
    }
6002
6003
    // Minimum size
6004
376k
    ImVec2 size_min = CalcWindowMinSize(window);
6005
376k
    return ImMax(new_size, size_min);
6006
376k
}
6007
6008
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6009
188k
{
6010
188k
    bool preserve_old_content_sizes = false;
6011
188k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6012
20.5k
        preserve_old_content_sizes = true;
6013
167k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6014
25.8k
        preserve_old_content_sizes = true;
6015
188k
    if (preserve_old_content_sizes)
6016
46.4k
    {
6017
46.4k
        *content_size_current = window->ContentSize;
6018
46.4k
        *content_size_ideal = window->ContentSizeIdeal;
6019
46.4k
        return;
6020
46.4k
    }
6021
6022
141k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6023
141k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6024
141k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6025
141k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6026
141k
}
6027
6028
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6029
188k
{
6030
188k
    ImGuiContext& g = *GImGui;
6031
188k
    ImGuiStyle& style = g.Style;
6032
188k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6033
188k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6034
188k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6035
188k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6036
188k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6037
0
    {
6038
        // Tooltip always resize
6039
0
        return size_desired;
6040
0
    }
6041
188k
    else
6042
188k
    {
6043
        // Maximum window size is determined by the viewport size or monitor size
6044
188k
        ImVec2 size_min = CalcWindowMinSize(window);
6045
188k
        ImVec2 size_max = (window->ViewportOwned || (window->Flags & ImGuiWindowFlags_ChildWindow)) ? ImVec2(FLT_MAX, FLT_MAX) : window->Viewport->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6046
188k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6047
188k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0)
6048
0
            size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6049
188k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6050
6051
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6052
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6053
188k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6054
188k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6055
188k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6056
188k
        if (will_have_scrollbar_x)
6057
49.0k
            size_auto_fit.y += style.ScrollbarSize;
6058
188k
        if (will_have_scrollbar_y)
6059
16.4k
            size_auto_fit.x += style.ScrollbarSize;
6060
188k
        return size_auto_fit;
6061
188k
    }
6062
188k
}
6063
6064
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6065
0
{
6066
0
    ImVec2 size_contents_current;
6067
0
    ImVec2 size_contents_ideal;
6068
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6069
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6070
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6071
0
    return size_final;
6072
0
}
6073
6074
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6075
167k
{
6076
167k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6077
0
        return ImGuiCol_PopupBg;
6078
167k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6079
49.0k
        return ImGuiCol_ChildBg;
6080
118k
    return ImGuiCol_WindowBg;
6081
167k
}
6082
6083
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6084
36
{
6085
36
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6086
36
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6087
36
    ImVec2 size_expected = pos_max - pos_min;
6088
36
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6089
36
    *out_pos = pos_min;
6090
36
    if (corner_norm.x == 0.0f)
6091
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6092
36
    if (corner_norm.y == 0.0f)
6093
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6094
36
    *out_size = size_constrained;
6095
36
}
6096
6097
// Data for resizing from resize grip / corner
6098
struct ImGuiResizeGripDef
6099
{
6100
    ImVec2  CornerPosN;
6101
    ImVec2  InnerDir;
6102
    int     AngleMin12, AngleMax12;
6103
};
6104
static const ImGuiResizeGripDef resize_grip_def[4] =
6105
{
6106
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6107
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6108
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6109
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6110
};
6111
6112
// Data for resizing from borders
6113
struct ImGuiResizeBorderDef
6114
{
6115
    ImVec2  InnerDir;               // Normal toward inside
6116
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6117
    float   OuterAngle;             // Angle toward outside
6118
};
6119
static const ImGuiResizeBorderDef resize_border_def[4] =
6120
{
6121
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6122
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6123
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6124
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6125
};
6126
6127
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6128
0
{
6129
0
    ImRect rect = window->Rect();
6130
0
    if (thickness == 0.0f)
6131
0
        rect.Max -= ImVec2(1, 1);
6132
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6133
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6134
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6135
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6136
0
    IM_ASSERT(0);
6137
0
    return ImRect();
6138
0
}
6139
6140
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6141
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6142
0
{
6143
0
    IM_ASSERT(n >= 0 && n < 4);
6144
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6145
0
    id = ImHashStr("#RESIZE", 0, id);
6146
0
    id = ImHashData(&n, sizeof(int), id);
6147
0
    return id;
6148
0
}
6149
6150
// Borders (Left, Right, Up, Down)
6151
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6152
0
{
6153
0
    IM_ASSERT(dir >= 0 && dir < 4);
6154
0
    int n = (int)dir + 4;
6155
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6156
0
    id = ImHashStr("#RESIZE", 0, id);
6157
0
    id = ImHashData(&n, sizeof(int), id);
6158
0
    return id;
6159
0
}
6160
6161
// Handle resize for: Resize Grips, Borders, Gamepad
6162
// Return true when using auto-fit (double-click on resize grip)
6163
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6164
167k
{
6165
167k
    ImGuiContext& g = *GImGui;
6166
167k
    ImGuiWindowFlags flags = window->Flags;
6167
6168
167k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6169
49.0k
        return false;
6170
118k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6171
69.6k
        return false;
6172
6173
49.0k
    int ret_auto_fit_mask = 0x00;
6174
49.0k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6175
49.0k
    const float grip_hover_inner_size = IM_TRUNC(grip_draw_size * 0.75f);
6176
49.0k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6177
6178
49.0k
    ImRect clamp_rect = visibility_rect;
6179
49.0k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6180
49.0k
    if (window_move_from_title_bar)
6181
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6182
6183
49.0k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6184
49.0k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6185
6186
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6187
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6188
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6189
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6190
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6191
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6192
49.0k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6193
49.0k
    if (clip_with_viewport_rect)
6194
49.0k
        window->ClipRect = window->Viewport->GetMainRect();
6195
6196
    // Resize grips and borders are on layer 1
6197
49.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6198
6199
    // Manual resize grips
6200
49.0k
    PushID("#RESIZE");
6201
98.1k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6202
49.0k
    {
6203
49.0k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6204
49.0k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6205
6206
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6207
49.0k
        bool hovered, held;
6208
49.0k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6209
49.0k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6210
49.0k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6211
49.0k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6212
49.0k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6213
49.0k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6214
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6215
49.0k
        if (hovered || held)
6216
42
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6217
6218
49.0k
        if (held && g.IO.MouseDoubleClicked[0])
6219
2
        {
6220
            // Auto-fit when double-clicking
6221
2
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6222
2
            ret_auto_fit_mask = 0x03; // Both axises
6223
2
            ClearActiveID();
6224
2
        }
6225
49.0k
        else if (held)
6226
36
        {
6227
            // Resize from any of the four corners
6228
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6229
36
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6230
36
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6231
36
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6232
36
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6233
36
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6234
36
        }
6235
6236
        // Only lower-left grip is visible before hovering/activating
6237
49.0k
        if (resize_grip_n == 0 || held || hovered)
6238
49.0k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6239
49.0k
    }
6240
6241
49.0k
    int resize_border_mask = 0x00;
6242
49.0k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6243
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6244
49.0k
    else
6245
49.0k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6246
245k
    for (int border_n = 0; border_n < 4; border_n++)
6247
196k
    {
6248
196k
        if ((resize_border_mask & (1 << border_n)) == 0)
6249
196k
            continue;
6250
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6251
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6252
6253
0
        bool hovered, held;
6254
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6255
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6256
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6257
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6258
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6259
0
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6260
0
            hovered = false;
6261
0
        if (hovered || held)
6262
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6263
0
        if (held && g.IO.MouseDoubleClicked[0])
6264
0
        {
6265
            // Double-clicking bottom or right border auto-fit on this axis
6266
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6267
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6268
0
            {
6269
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6270
0
                ret_auto_fit_mask |= (1 << axis);
6271
0
                hovered = held = false; // So border doesn't show highlighted at new position
6272
0
            }
6273
0
            ClearActiveID();
6274
0
        }
6275
0
        else if (held)
6276
0
        {
6277
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6278
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6279
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6280
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6281
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6282
0
            {
6283
0
                g.WindowResizeBorderExpectedRect = border_rect;
6284
0
                g.WindowResizeRelativeMode = false;
6285
0
            }
6286
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6287
0
                g.WindowResizeRelativeMode = true;
6288
6289
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6290
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6291
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6292
6293
            // Use absolute mode position
6294
0
            ImVec2 border_target = window->Pos;
6295
0
            border_target[axis] = border_target_abs_mode_for_axis;
6296
6297
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6298
0
            bool ignore_resize = false;
6299
0
            if (g.WindowResizeRelativeMode)
6300
0
            {
6301
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6302
0
                border_target[axis] = border_target_rel_mode_for_axis;
6303
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6304
0
                    ignore_resize = true;
6305
0
            }
6306
6307
            // Clamp, apply
6308
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6309
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6310
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6311
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6312
0
            {
6313
0
                if ((flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (flags & ImGuiWindowFlags_NoScrollbar))
6314
0
                    border_target.x = ImClamp(border_target.x, window->ParentWindow->InnerClipRect.Min.x, window->ParentWindow->InnerClipRect.Max.x);
6315
0
                if (flags & ImGuiWindowFlags_NoScrollbar)
6316
0
                    border_target.y = ImClamp(border_target.y, window->ParentWindow->InnerClipRect.Min.y, window->ParentWindow->InnerClipRect.Max.y);
6317
0
            }
6318
0
            if (!ignore_resize)
6319
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6320
0
        }
6321
0
        if (hovered)
6322
0
            *border_hovered = border_n;
6323
0
        if (held)
6324
0
            *border_held = border_n;
6325
0
    }
6326
49.0k
    PopID();
6327
6328
    // Restore nav layer
6329
49.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6330
6331
    // Navigation resize (keyboard/gamepad)
6332
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6333
    // Not even sure the callback works here.
6334
49.0k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6335
0
    {
6336
0
        ImVec2 nav_resize_dir;
6337
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6338
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6339
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6340
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6341
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6342
0
        {
6343
0
            const float NAV_RESIZE_SPEED = 600.0f;
6344
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6345
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6346
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6347
0
            g.NavWindowingToggleLayer = false;
6348
0
            g.NavDisableMouseHover = true;
6349
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6350
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6351
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6352
0
            {
6353
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6354
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6355
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6356
0
            }
6357
0
        }
6358
0
    }
6359
6360
    // Apply back modified position/size to window
6361
49.0k
    if (size_target.x != FLT_MAX)
6362
38
        window->Size.x = window->SizeFull.x = size_target.x;
6363
49.0k
    if (size_target.y != FLT_MAX)
6364
38
        window->Size.y = window->SizeFull.y = size_target.y;
6365
49.0k
    if (pos_target.x != FLT_MAX)
6366
36
        window->Pos.x = ImTrunc(pos_target.x);
6367
49.0k
    if (pos_target.y != FLT_MAX)
6368
36
        window->Pos.y = ImTrunc(pos_target.y);
6369
49.0k
    if (size_target.x != FLT_MAX || size_target.y != FLT_MAX || pos_target.x != FLT_MAX || pos_target.y != FLT_MAX)
6370
38
        MarkIniSettingsDirty(window);
6371
6372
    // Recalculate next expected border expected coordinates
6373
49.0k
    if (*border_held != -1)
6374
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6375
6376
49.0k
    return ret_auto_fit_mask;
6377
118k
}
6378
6379
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6380
139k
{
6381
139k
    ImGuiContext& g = *GImGui;
6382
139k
    ImVec2 size_for_clamping = window->Size;
6383
139k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6384
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6385
139k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6386
139k
}
6387
6388
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6389
167k
{
6390
167k
    ImGuiContext& g = *GImGui;
6391
167k
    float rounding = window->WindowRounding;
6392
167k
    float border_size = window->WindowBorderSize;
6393
167k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6394
145k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6395
6396
167k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6397
0
    {
6398
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6399
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6400
0
        const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6401
0
        const ImU32 border_col = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6402
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6403
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6404
0
        window->DrawList->PathStroke(border_col, 0, ImMax(2.0f, border_size)); // Thicker than usual
6405
0
    }
6406
167k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6407
0
    {
6408
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6409
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6410
0
    }
6411
167k
}
6412
6413
// Draw background and borders
6414
// Draw and handle scrollbars
6415
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6416
188k
{
6417
188k
    ImGuiContext& g = *GImGui;
6418
188k
    ImGuiStyle& style = g.Style;
6419
188k
    ImGuiWindowFlags flags = window->Flags;
6420
6421
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6422
188k
    IM_ASSERT(window->BeginCount == 0);
6423
188k
    window->SkipItems = false;
6424
6425
    // Draw window + handle manual resize
6426
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6427
188k
    const float window_rounding = window->WindowRounding;
6428
188k
    const float window_border_size = window->WindowBorderSize;
6429
188k
    if (window->Collapsed)
6430
20.5k
    {
6431
        // Title bar only
6432
20.5k
        const float backup_border_size = style.FrameBorderSize;
6433
20.5k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6434
20.5k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6435
20.5k
        if (window->ViewportOwned)
6436
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6437
20.5k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6438
20.5k
        g.Style.FrameBorderSize = backup_border_size;
6439
20.5k
    }
6440
167k
    else
6441
167k
    {
6442
        // Window background
6443
167k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6444
167k
        {
6445
167k
            bool is_docking_transparent_payload = false;
6446
167k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6447
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6448
0
                    is_docking_transparent_payload = true;
6449
6450
167k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6451
167k
            if (window->ViewportOwned)
6452
0
            {
6453
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6454
0
                if (is_docking_transparent_payload)
6455
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6456
0
            }
6457
167k
            else
6458
167k
            {
6459
                // Adjust alpha. For docking
6460
167k
                bool override_alpha = false;
6461
167k
                float alpha = 1.0f;
6462
167k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6463
0
                {
6464
0
                    alpha = g.NextWindowData.BgAlphaVal;
6465
0
                    override_alpha = true;
6466
0
                }
6467
167k
                if (is_docking_transparent_payload)
6468
0
                {
6469
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6470
0
                    override_alpha = true;
6471
0
                }
6472
167k
                if (override_alpha)
6473
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6474
167k
            }
6475
6476
            // Render, for docked windows and host windows we ensure bg goes before decorations
6477
167k
            if (window->DockIsActive)
6478
0
                window->DockNode->LastBgColor = bg_col;
6479
167k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6480
167k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6481
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6482
167k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6483
167k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6484
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6485
167k
        }
6486
167k
        if (window->DockIsActive)
6487
0
            window->DockNode->IsBgDrawnThisFrame = true;
6488
6489
        // Title bar
6490
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6491
        // in order for their pos/size to be matching their undocking state.)
6492
167k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6493
118k
        {
6494
118k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6495
118k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6496
118k
        }
6497
6498
        // Menu bar
6499
167k
        if (flags & ImGuiWindowFlags_MenuBar)
6500
0
        {
6501
0
            ImRect menu_bar_rect = window->MenuBarRect();
6502
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6503
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6504
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6505
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6506
0
        }
6507
6508
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6509
167k
        ImGuiDockNode* node = window->DockNode;
6510
167k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6511
0
        {
6512
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6513
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6514
0
            ImVec2 p = node->Pos;
6515
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6516
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6517
0
            KeepAliveID(unhide_id);
6518
0
            bool hovered, held;
6519
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6520
0
                node->WantHiddenTabBarToggle = true;
6521
0
            else if (held && IsMouseDragging(0))
6522
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6523
6524
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6525
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6526
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6527
0
        }
6528
6529
        // Scrollbars
6530
167k
        if (window->ScrollbarX)
6531
49.0k
            Scrollbar(ImGuiAxis_X);
6532
167k
        if (window->ScrollbarY)
6533
49.5k
            Scrollbar(ImGuiAxis_Y);
6534
6535
        // Render resize grips (after their input handling so we don't have a frame of latency)
6536
167k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6537
118k
        {
6538
237k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6539
118k
            {
6540
118k
                const ImU32 col = resize_grip_col[resize_grip_n];
6541
118k
                if ((col & IM_COL32_A_MASK) == 0)
6542
69.6k
                    continue;
6543
49.0k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6544
49.0k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6545
49.0k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6546
49.0k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6547
49.0k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6548
49.0k
                window->DrawList->PathFillConvex(col);
6549
49.0k
            }
6550
118k
        }
6551
6552
        // Borders (for dock node host they will be rendered over after the tab bar)
6553
167k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6554
167k
            RenderWindowOuterBorders(window);
6555
167k
    }
6556
188k
}
6557
6558
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6559
// Render title text, collapse button, close button
6560
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6561
139k
{
6562
139k
    ImGuiContext& g = *GImGui;
6563
139k
    ImGuiStyle& style = g.Style;
6564
139k
    ImGuiWindowFlags flags = window->Flags;
6565
6566
139k
    const bool has_close_button = (p_open != NULL);
6567
139k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6568
6569
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6570
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6571
139k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6572
139k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6573
139k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6574
6575
    // Layout buttons
6576
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6577
139k
    float pad_l = style.FramePadding.x;
6578
139k
    float pad_r = style.FramePadding.x;
6579
139k
    float button_sz = g.FontSize;
6580
139k
    ImVec2 close_button_pos;
6581
139k
    ImVec2 collapse_button_pos;
6582
139k
    if (has_close_button)
6583
0
    {
6584
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6585
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6586
0
    }
6587
139k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6588
0
    {
6589
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6590
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6591
0
    }
6592
139k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6593
139k
    {
6594
139k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6595
139k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6596
139k
    }
6597
6598
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6599
139k
    if (has_collapse_button)
6600
139k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6601
17
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6602
6603
    // Close button
6604
139k
    if (has_close_button)
6605
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6606
0
            *p_open = false;
6607
6608
139k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6609
139k
    g.CurrentItemFlags = item_flags_backup;
6610
6611
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6612
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6613
139k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6614
139k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6615
6616
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6617
    // while uncentered title text will still reach edges correctly.
6618
139k
    if (pad_l > style.FramePadding.x)
6619
139k
        pad_l += g.Style.ItemInnerSpacing.x;
6620
139k
    if (pad_r > style.FramePadding.x)
6621
0
        pad_r += g.Style.ItemInnerSpacing.x;
6622
139k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6623
0
    {
6624
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6625
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6626
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6627
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6628
0
    }
6629
6630
139k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6631
139k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6632
139k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6633
0
    {
6634
0
        ImVec2 marker_pos;
6635
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6636
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6637
0
        if (marker_pos.x > layout_r.Min.x)
6638
0
        {
6639
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6640
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6641
0
        }
6642
0
    }
6643
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6644
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6645
139k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6646
139k
}
6647
6648
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6649
188k
{
6650
188k
    window->ParentWindow = parent_window;
6651
188k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6652
188k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6653
49.0k
    {
6654
49.0k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6655
49.0k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6656
49.0k
            window->RootWindow = parent_window->RootWindow;
6657
49.0k
    }
6658
188k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6659
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6660
188k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6661
49.0k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6662
188k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6663
0
    {
6664
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6665
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6666
0
    }
6667
188k
}
6668
6669
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6670
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6671
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6672
// - WindowA            // FindBlockingModal() returns Modal1
6673
//   - WindowB          //                  .. returns Modal1
6674
//   - Modal1           //                  .. returns Modal2
6675
//      - WindowC       //                  .. returns Modal2
6676
//          - WindowD   //                  .. returns Modal2
6677
//          - Modal2    //                  .. returns Modal2
6678
//            - WindowE //                  .. returns NULL
6679
// Notes:
6680
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6681
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6682
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6683
178
{
6684
178
    ImGuiContext& g = *GImGui;
6685
178
    if (g.OpenPopupStack.Size <= 0)
6686
178
        return NULL;
6687
6688
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6689
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6690
0
    {
6691
0
        ImGuiWindow* popup_window = popup_data.Window;
6692
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6693
0
            continue;
6694
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6695
0
            continue;
6696
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6697
0
            return popup_window;
6698
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6699
0
            continue;
6700
0
        return popup_window;                                        // Place window right below first block modal
6701
0
    }
6702
0
    return NULL;
6703
0
}
6704
6705
// Push a new Dear ImGui window to add widgets to.
6706
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6707
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6708
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6709
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6710
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6711
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6712
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6713
188k
{
6714
188k
    ImGuiContext& g = *GImGui;
6715
188k
    const ImGuiStyle& style = g.Style;
6716
188k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6717
188k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6718
188k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6719
6720
    // Find or create
6721
188k
    ImGuiWindow* window = FindWindowByName(name);
6722
188k
    const bool window_just_created = (window == NULL);
6723
188k
    if (window_just_created)
6724
3
        window = CreateNewWindow(name, flags);
6725
6726
    // Automatically disable manual moving/resizing when NoInputs is set
6727
188k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6728
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6729
6730
188k
    if (flags & ImGuiWindowFlags_NavFlattened)
6731
188k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6732
6733
188k
    const int current_frame = g.FrameCount;
6734
188k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6735
188k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6736
6737
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6738
188k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6739
188k
    if (flags & ImGuiWindowFlags_Popup)
6740
0
    {
6741
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6742
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6743
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6744
0
    }
6745
6746
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6747
188k
    const bool window_was_appearing = window->Appearing;
6748
188k
    if (first_begin_of_the_frame)
6749
188k
    {
6750
188k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6751
188k
        window->Appearing = window_just_activated_by_user;
6752
188k
        if (window->Appearing)
6753
18
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6754
188k
        window->FlagsPreviousFrame = window->Flags;
6755
188k
        window->Flags = (ImGuiWindowFlags)flags;
6756
188k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6757
188k
        window->LastFrameActive = current_frame;
6758
188k
        window->LastTimeActive = (float)g.Time;
6759
188k
        window->BeginOrderWithinParent = 0;
6760
188k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6761
188k
    }
6762
0
    else
6763
0
    {
6764
0
        flags = window->Flags;
6765
0
    }
6766
6767
    // Docking
6768
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6769
188k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6770
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6771
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6772
188k
    if (first_begin_of_the_frame)
6773
188k
    {
6774
188k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6775
188k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6776
188k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6777
188k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6778
188k
        if (has_dock_node || new_auto_dock_node)
6779
0
        {
6780
0
            BeginDocked(window, p_open);
6781
0
            flags = window->Flags;
6782
0
            if (window->DockIsActive)
6783
0
            {
6784
0
                IM_ASSERT(window->DockNode != NULL);
6785
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6786
0
            }
6787
6788
            // Amend the Appearing flag
6789
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6790
0
            {
6791
0
                window->Appearing = true;
6792
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6793
0
            }
6794
0
        }
6795
188k
        else
6796
188k
        {
6797
188k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6798
188k
        }
6799
188k
    }
6800
6801
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6802
188k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6803
188k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6804
188k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6805
6806
    // We allow window memory to be compacted so recreate the base stack when needed.
6807
188k
    if (window->IDStack.Size == 0)
6808
3
        window->IDStack.push_back(window->ID);
6809
6810
    // Add to stack
6811
188k
    g.CurrentWindow = window;
6812
188k
    ImGuiWindowStackData window_stack_data;
6813
188k
    window_stack_data.Window = window;
6814
188k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6815
188k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6816
188k
    g.CurrentWindowStack.push_back(window_stack_data);
6817
188k
    if (flags & ImGuiWindowFlags_ChildMenu)
6818
0
        g.BeginMenuCount++;
6819
6820
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6821
188k
    if (first_begin_of_the_frame)
6822
188k
    {
6823
188k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6824
188k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6825
188k
    }
6826
6827
    // Add to focus scope stack
6828
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6829
188k
    if ((flags & ImGuiWindowFlags_NavFlattened) == 0)
6830
188k
        PushFocusScope(window->ID);
6831
188k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6832
188k
    g.CurrentWindow = NULL;
6833
6834
    // Add to popup stack
6835
188k
    if (flags & ImGuiWindowFlags_Popup)
6836
0
    {
6837
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6838
0
        popup_ref.Window = window;
6839
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6840
0
        g.BeginPopupStack.push_back(popup_ref);
6841
0
        window->PopupId = popup_ref.PopupId;
6842
0
    }
6843
6844
    // Process SetNextWindow***() calls
6845
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6846
188k
    bool window_pos_set_by_api = false;
6847
188k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6848
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6849
0
    {
6850
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6851
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6852
0
        {
6853
            // May be processed on the next frame if this is our first frame and we are measuring size
6854
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6855
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6856
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6857
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6858
0
        }
6859
0
        else
6860
0
        {
6861
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6862
0
        }
6863
0
    }
6864
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6865
118k
    {
6866
118k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6867
118k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6868
118k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6869
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
6870
118k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6871
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
6872
118k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6873
118k
    }
6874
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6875
0
    {
6876
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6877
0
        {
6878
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6879
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6880
0
        }
6881
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6882
0
        {
6883
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6884
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6885
0
        }
6886
0
    }
6887
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6888
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6889
188k
    else if (first_begin_of_the_frame)
6890
188k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6891
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6892
0
        window->WindowClass = g.NextWindowData.WindowClass;
6893
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6894
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6895
188k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6896
0
        FocusWindow(window);
6897
188k
    if (window->Appearing)
6898
18
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6899
6900
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6901
188k
    if (first_begin_of_the_frame)
6902
188k
    {
6903
        // Initialize
6904
188k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6905
188k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6906
188k
        window->Active = true;
6907
188k
        window->HasCloseButton = (p_open != NULL);
6908
188k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6909
188k
        window->IDStack.resize(1);
6910
188k
        window->DrawList->_ResetForNewFrame();
6911
188k
        window->DC.CurrentTableIdx = -1;
6912
188k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6913
0
        {
6914
0
            window->DrawList->ChannelsSplit(2);
6915
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6916
0
        }
6917
6918
        // Restore buffer capacity when woken from a compacted state, to avoid
6919
188k
        if (window->MemoryCompacted)
6920
3
            GcAwakeTransientWindowBuffers(window);
6921
6922
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6923
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6924
188k
        bool window_title_visible_elsewhere = false;
6925
188k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6926
0
            window_title_visible_elsewhere = true;
6927
188k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6928
0
            window_title_visible_elsewhere = true;
6929
188k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6930
0
        {
6931
0
            size_t buf_len = (size_t)window->NameBufLen;
6932
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6933
0
            window->NameBufLen = (int)buf_len;
6934
0
        }
6935
6936
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6937
6938
        // Update contents size from last frame for auto-fitting (or use explicit size)
6939
188k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6940
6941
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6942
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6943
        // it has a single usage before this code block and may be set below before it is finally checked.
6944
188k
        if (window->HiddenFramesCanSkipItems > 0)
6945
25.8k
            window->HiddenFramesCanSkipItems--;
6946
188k
        if (window->HiddenFramesCannotSkipItems > 0)
6947
2
            window->HiddenFramesCannotSkipItems--;
6948
188k
        if (window->HiddenFramesForRenderOnly > 0)
6949
0
            window->HiddenFramesForRenderOnly--;
6950
6951
        // Hide new windows for one frame until they calculate their size
6952
188k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6953
1
            window->HiddenFramesCannotSkipItems = 1;
6954
6955
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6956
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6957
188k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6958
0
        {
6959
0
            window->HiddenFramesCannotSkipItems = 1;
6960
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6961
0
            {
6962
0
                if (!window_size_x_set_by_api)
6963
0
                    window->Size.x = window->SizeFull.x = 0.f;
6964
0
                if (!window_size_y_set_by_api)
6965
0
                    window->Size.y = window->SizeFull.y = 0.f;
6966
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6967
0
            }
6968
0
        }
6969
6970
        // SELECT VIEWPORT
6971
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6972
6973
188k
        WindowSelectViewport(window);
6974
188k
        SetCurrentViewport(window, window->Viewport);
6975
188k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6976
188k
        SetCurrentWindow(window);
6977
188k
        flags = window->Flags;
6978
6979
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6980
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6981
6982
188k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
6983
49.0k
            window->WindowBorderSize = style.ChildBorderSize;
6984
139k
        else
6985
139k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6986
188k
        window->WindowPadding = style.WindowPadding;
6987
188k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
6988
22.7k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6989
6990
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6991
188k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6992
188k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6993
6994
188k
        bool use_current_size_for_scrollbar_x = window_just_created;
6995
188k
        bool use_current_size_for_scrollbar_y = window_just_created;
6996
6997
        // Collapse window by double-clicking on title bar
6998
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6999
188k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7000
139k
        {
7001
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7002
139k
            ImRect title_bar_rect = window->TitleBarRect();
7003
139k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
7004
15
                window->WantCollapseToggle = true;
7005
139k
            if (window->WantCollapseToggle)
7006
32
            {
7007
32
                window->Collapsed = !window->Collapsed;
7008
32
                if (!window->Collapsed)
7009
16
                    use_current_size_for_scrollbar_y = true;
7010
32
                MarkIniSettingsDirty(window);
7011
32
            }
7012
139k
        }
7013
49.0k
        else
7014
49.0k
        {
7015
49.0k
            window->Collapsed = false;
7016
49.0k
        }
7017
188k
        window->WantCollapseToggle = false;
7018
7019
        // SIZE
7020
7021
        // Outer Decoration Sizes
7022
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7023
188k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7024
188k
        window->DecoOuterSizeX1 = 0.0f;
7025
188k
        window->DecoOuterSizeX2 = 0.0f;
7026
188k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7027
188k
        window->DecoOuterSizeY2 = 0.0f;
7028
188k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7029
7030
        // Calculate auto-fit size, handle automatic resize
7031
188k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7032
188k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7033
0
        {
7034
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7035
0
            if (!window_size_x_set_by_api)
7036
0
            {
7037
0
                window->SizeFull.x = size_auto_fit.x;
7038
0
                use_current_size_for_scrollbar_x = true;
7039
0
            }
7040
0
            if (!window_size_y_set_by_api)
7041
0
            {
7042
0
                window->SizeFull.y = size_auto_fit.y;
7043
0
                use_current_size_for_scrollbar_y = true;
7044
0
            }
7045
0
        }
7046
188k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7047
2
        {
7048
            // Auto-fit may only grow window during the first few frames
7049
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7050
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7051
2
            {
7052
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7053
2
                use_current_size_for_scrollbar_x = true;
7054
2
            }
7055
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7056
2
            {
7057
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7058
2
                use_current_size_for_scrollbar_y = true;
7059
2
            }
7060
2
            if (!window->Collapsed)
7061
2
                MarkIniSettingsDirty(window);
7062
2
        }
7063
7064
        // Apply minimum/maximum window size constraints and final size
7065
188k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7066
188k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7067
7068
        // POSITION
7069
7070
        // Popup latch its initial position, will position itself when it appears next frame
7071
188k
        if (window_just_activated_by_user)
7072
18
        {
7073
18
            window->AutoPosLastDirection = ImGuiDir_None;
7074
18
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7075
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7076
18
        }
7077
7078
        // Position child window
7079
188k
        if (flags & ImGuiWindowFlags_ChildWindow)
7080
49.0k
        {
7081
49.0k
            IM_ASSERT(parent_window && parent_window->Active);
7082
49.0k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7083
49.0k
            parent_window->DC.ChildWindows.push_back(window);
7084
49.0k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7085
49.0k
                window->Pos = parent_window->DC.CursorPos;
7086
49.0k
        }
7087
7088
188k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7089
188k
        if (window_pos_with_pivot)
7090
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7091
188k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7092
0
            window->Pos = FindBestWindowPosForPopup(window);
7093
188k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7094
0
            window->Pos = FindBestWindowPosForPopup(window);
7095
188k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7096
0
            window->Pos = FindBestWindowPosForPopup(window);
7097
7098
        // Late create viewport if we don't fit within our current host viewport.
7099
188k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7100
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7101
0
            {
7102
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7103
                //ImGuiViewport* old_viewport = window->Viewport;
7104
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7105
7106
                // FIXME-DPI
7107
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7108
0
                SetCurrentViewport(window, window->Viewport);
7109
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7110
0
                SetCurrentWindow(window);
7111
0
            }
7112
7113
188k
        if (window->ViewportOwned)
7114
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7115
7116
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7117
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7118
188k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7119
188k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7120
188k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7121
188k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7122
7123
        // Clamp position/size so window stays visible within its viewport or monitor
7124
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7125
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7126
188k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7127
139k
        {
7128
139k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7129
139k
            {
7130
139k
                ClampWindowPos(window, visibility_rect);
7131
139k
            }
7132
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7133
0
            {
7134
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7135
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7136
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7137
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7138
0
                ClampWindowPos(window, visibility_rect);
7139
0
            }
7140
139k
        }
7141
188k
        window->Pos = ImTrunc(window->Pos);
7142
7143
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7144
        // Large values tend to lead to variety of artifacts and are not recommended.
7145
188k
        if (window->ViewportOwned || window->DockIsActive)
7146
0
            window->WindowRounding = 0.0f;
7147
188k
        else
7148
188k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7149
7150
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7151
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7152
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7153
7154
        // Apply window focus (new and reactivated windows are moved to front)
7155
188k
        bool want_focus = false;
7156
188k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7157
18
        {
7158
18
            if (flags & ImGuiWindowFlags_Popup)
7159
0
                want_focus = true;
7160
18
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7161
2
                want_focus = true;
7162
18
        }
7163
7164
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7165
#ifdef IMGUI_ENABLE_TEST_ENGINE
7166
        if (g.TestEngineHookItems)
7167
        {
7168
            IM_ASSERT(window->IDStack.Size == 1);
7169
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7170
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7171
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7172
            window->IDStack.Size = 1;
7173
        }
7174
#endif
7175
7176
        // Decide if we are going to handle borders and resize grips
7177
188k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7178
7179
        // Handle manual resize: Resize Grips, Borders, Gamepad
7180
188k
        int border_hovered = -1, border_held = -1;
7181
188k
        ImU32 resize_grip_col[4] = {};
7182
188k
        const int resize_grip_count = (window->Flags & ImGuiWindowFlags_ChildWindow) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7183
188k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7184
188k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7185
167k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7186
2
            {
7187
2
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7188
2
                    use_current_size_for_scrollbar_x = true;
7189
2
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7190
2
                    use_current_size_for_scrollbar_y = true;
7191
2
            }
7192
188k
        window->ResizeBorderHovered = (signed char)border_hovered;
7193
188k
        window->ResizeBorderHeld = (signed char)border_held;
7194
7195
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7196
188k
        if (window->ViewportOwned)
7197
0
        {
7198
0
            if (!window->Viewport->PlatformRequestMove)
7199
0
                window->Viewport->Pos = window->Pos;
7200
0
            if (!window->Viewport->PlatformRequestResize)
7201
0
                window->Viewport->Size = window->Size;
7202
0
            window->Viewport->UpdateWorkRect();
7203
0
            viewport_rect = window->Viewport->GetMainRect();
7204
0
        }
7205
7206
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7207
188k
        window->ViewportPos = window->Viewport->Pos;
7208
7209
        // SCROLLBAR VISIBILITY
7210
7211
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7212
188k
        if (!window->Collapsed)
7213
167k
        {
7214
            // When reading the current size we need to read it after size constraints have been applied.
7215
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7216
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7217
167k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7218
167k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7219
167k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7220
167k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7221
167k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7222
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7223
167k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7224
167k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7225
167k
            if (window->ScrollbarX && !window->ScrollbarY)
7226
4.49k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7227
167k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7228
7229
            // Amend the partially filled window->DecorationXXX values.
7230
167k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7231
167k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7232
167k
        }
7233
7234
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7235
        // Update various regions. Variables they depend on should be set above in this function.
7236
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7237
7238
        // Outer rectangle
7239
        // Not affected by window border size. Used by:
7240
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7241
        // - Begin() initial clipping rect for drawing window background and borders.
7242
        // - Begin() clipping whole child
7243
188k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7244
188k
        const ImRect outer_rect = window->Rect();
7245
188k
        const ImRect title_bar_rect = window->TitleBarRect();
7246
188k
        window->OuterRectClipped = outer_rect;
7247
188k
        if (window->DockIsActive)
7248
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7249
188k
        window->OuterRectClipped.ClipWith(host_rect);
7250
7251
        // Inner rectangle
7252
        // Not affected by window border size. Used by:
7253
        // - InnerClipRect
7254
        // - ScrollToRectEx()
7255
        // - NavUpdatePageUpPageDown()
7256
        // - Scrollbar()
7257
188k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7258
188k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7259
188k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7260
188k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7261
7262
        // Inner clipping rectangle.
7263
        // Will extend a little bit outside the normal work region.
7264
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7265
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7266
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7267
        // Affected by window/frame border size. Used by:
7268
        // - Begin() initial clip rect
7269
188k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7270
188k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7271
188k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7272
188k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7273
188k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7274
188k
        window->InnerClipRect.ClipWithFull(host_rect);
7275
7276
        // Default item width. Make it proportional to window size if window manually resizes
7277
188k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7278
188k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7279
0
        else
7280
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7281
7282
        // SCROLLING
7283
7284
        // Lock down maximum scrolling
7285
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7286
        // for right/bottom aligned items without creating a scrollbar.
7287
188k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7288
188k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7289
7290
        // Apply scrolling
7291
188k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7292
188k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7293
188k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7294
7295
        // DRAWING
7296
7297
        // Setup draw list and outer clipping rectangle
7298
188k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7299
188k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7300
188k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7301
7302
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7303
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7304
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7305
188k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7306
188k
        if (is_undocked_or_docked_visible)
7307
188k
        {
7308
188k
            bool render_decorations_in_parent = false;
7309
188k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7310
49.0k
            {
7311
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7312
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7313
49.0k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7314
49.0k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7315
49.0k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7316
49.0k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7317
49.0k
                    render_decorations_in_parent = true;
7318
49.0k
            }
7319
188k
            if (render_decorations_in_parent)
7320
49.0k
                window->DrawList = parent_window->DrawList;
7321
7322
            // Handle title bar, scrollbar, resize grips and resize borders
7323
188k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7324
188k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7325
188k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7326
7327
188k
            if (render_decorations_in_parent)
7328
49.0k
                window->DrawList = &window->DrawListInst;
7329
188k
        }
7330
7331
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7332
7333
        // Work rectangle.
7334
        // Affected by window padding and border size. Used by:
7335
        // - Columns() for right-most edge
7336
        // - TreeNode(), CollapsingHeader() for right-most edge
7337
        // - BeginTabBar() for right-most edge
7338
188k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7339
188k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7340
188k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7341
188k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7342
188k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7343
188k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7344
188k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7345
188k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7346
188k
        window->ParentWorkRect = window->WorkRect;
7347
7348
        // [LEGACY] Content Region
7349
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7350
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7351
        // Used by:
7352
        // - Mouse wheel scrolling + many other things
7353
188k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7354
188k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7355
188k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7356
188k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7357
7358
        // Setup drawing context
7359
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7360
188k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7361
188k
        window->DC.GroupOffset.x = 0.0f;
7362
188k
        window->DC.ColumnsOffset.x = 0.0f;
7363
7364
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7365
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7366
188k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7367
188k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7368
188k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7369
188k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7370
188k
        window->DC.CursorPos = window->DC.CursorStartPos;
7371
188k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7372
188k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7373
188k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7374
188k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7375
188k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7376
188k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7377
7378
188k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7379
188k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7380
188k
        window->DC.NavLayersActiveMaskNext = 0x00;
7381
188k
        window->DC.NavIsScrollPushableX = true;
7382
188k
        window->DC.NavHideHighlightOneFrame = false;
7383
188k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7384
7385
188k
        window->DC.MenuBarAppending = false;
7386
188k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7387
188k
        window->DC.TreeDepth = 0;
7388
188k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7389
188k
        window->DC.ChildWindows.resize(0);
7390
188k
        window->DC.StateStorage = &window->StateStorage;
7391
188k
        window->DC.CurrentColumns = NULL;
7392
188k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7393
188k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7394
7395
188k
        window->DC.ItemWidth = window->ItemWidthDefault;
7396
188k
        window->DC.TextWrapPos = -1.0f; // disabled
7397
188k
        window->DC.ItemWidthStack.resize(0);
7398
188k
        window->DC.TextWrapPosStack.resize(0);
7399
7400
188k
        if (window->AutoFitFramesX > 0)
7401
2
            window->AutoFitFramesX--;
7402
188k
        if (window->AutoFitFramesY > 0)
7403
2
            window->AutoFitFramesY--;
7404
7405
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7406
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7407
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7408
        // - Position window behind the modal that is not a begin-parent of this window.
7409
188k
        if (want_focus)
7410
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7411
188k
        if (want_focus && window == g.NavWindow)
7412
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7413
7414
        // Close requested by platform window (apply to all windows in this viewport)
7415
188k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7416
0
        {
7417
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7418
0
            *p_open = false;
7419
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7420
0
        }
7421
7422
        // Title bar
7423
188k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7424
139k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7425
7426
        // Clear hit test shape every frame
7427
188k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7428
7429
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7430
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7431
        // Maybe we can support CTRL+C on every element?
7432
        /*
7433
        //if (g.NavWindow == window && g.ActiveId == 0)
7434
        if (g.ActiveId == window->MoveId)
7435
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7436
                LogToClipboard();
7437
        */
7438
7439
188k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7440
188k
        {
7441
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7442
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7443
188k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7444
780
                BeginDockableDragDropSource(window);
7445
7446
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7447
188k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7448
1.20k
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7449
777
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7450
777
                        BeginDockableDragDropTarget(window);
7451
188k
        }
7452
7453
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7454
        // This is useful to allow creating context menus on title bar only, etc.
7455
188k
        if (window->DockIsActive)
7456
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7457
188k
        else
7458
188k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7459
7460
        // [DEBUG]
7461
188k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7462
188k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7463
0
            DebugLocateItemResolveWithLastItem();
7464
188k
#endif
7465
7466
        // [Test Engine] Register title bar / tab with MoveId.
7467
#ifdef IMGUI_ENABLE_TEST_ENGINE
7468
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7469
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7470
#endif
7471
188k
    }
7472
0
    else
7473
0
    {
7474
        // Append
7475
0
        SetCurrentViewport(window, window->Viewport);
7476
0
        SetCurrentWindow(window);
7477
0
    }
7478
7479
188k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7480
188k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7481
7482
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7483
188k
    window->WriteAccessed = false;
7484
188k
    window->BeginCount++;
7485
188k
    g.NextWindowData.ClearFlags();
7486
7487
    // Update visibility
7488
188k
    if (first_begin_of_the_frame)
7489
188k
    {
7490
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7491
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7492
        // This is analogous to regular windows being hidden from one frame.
7493
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7494
188k
        if (window->DockIsActive && !window->DockTabIsVisible)
7495
0
        {
7496
0
            if (window->LastFrameJustFocused == g.FrameCount)
7497
0
                window->HiddenFramesCannotSkipItems = 1;
7498
0
            else
7499
0
                window->HiddenFramesCanSkipItems = 1;
7500
0
        }
7501
7502
188k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7503
49.0k
        {
7504
            // Child window can be out of sight and have "negative" clip windows.
7505
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7506
49.0k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7507
49.0k
            const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7508
49.0k
            if (!g.LogEnabled && !nav_request)
7509
49.0k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7510
25.8k
                {
7511
25.8k
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7512
0
                        window->HiddenFramesCannotSkipItems = 1;
7513
25.8k
                    else
7514
25.8k
                        window->HiddenFramesCanSkipItems = 1;
7515
25.8k
                }
7516
7517
            // Hide along with parent or if parent is collapsed
7518
49.0k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7519
0
                window->HiddenFramesCanSkipItems = 1;
7520
49.0k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7521
1
                window->HiddenFramesCannotSkipItems = 1;
7522
49.0k
        }
7523
7524
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7525
188k
        if (style.Alpha <= 0.0f)
7526
0
            window->HiddenFramesCanSkipItems = 1;
7527
7528
        // Update the Hidden flag
7529
188k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7530
188k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7531
7532
        // Disable inputs for requested number of frames
7533
188k
        if (window->DisableInputsFrames > 0)
7534
0
        {
7535
0
            window->DisableInputsFrames--;
7536
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7537
0
        }
7538
7539
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7540
188k
        bool skip_items = false;
7541
188k
        if (window->Collapsed || !window->Active || hidden_regular)
7542
46.4k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7543
46.4k
                skip_items = true;
7544
188k
        window->SkipItems = skip_items;
7545
7546
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7547
188k
        if (window->SkipItems)
7548
46.4k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7549
7550
        // Sanity check: there are two spots which can set Appearing = true
7551
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7552
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7553
188k
        if (window->SkipItems && !window->Appearing)
7554
188k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7555
188k
    }
7556
7557
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7558
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7559
188k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7560
0
    {
7561
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7562
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7563
0
        return false;
7564
0
    }
7565
7566
188k
    return !window->SkipItems;
7567
188k
}
7568
7569
void ImGui::End()
7570
188k
{
7571
188k
    ImGuiContext& g = *GImGui;
7572
188k
    ImGuiWindow* window = g.CurrentWindow;
7573
7574
    // Error checking: verify that user hasn't called End() too many times!
7575
188k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7576
0
    {
7577
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7578
0
        return;
7579
0
    }
7580
188k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7581
7582
    // Error checking: verify that user doesn't directly call End() on a child window.
7583
188k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7584
188k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7585
7586
    // Close anything that is open
7587
188k
    if (window->DC.CurrentColumns)
7588
0
        EndColumns();
7589
188k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7590
188k
        PopClipRect();
7591
188k
    if ((window->Flags & ImGuiWindowFlags_NavFlattened) == 0)
7592
188k
        PopFocusScope();
7593
7594
    // Stop logging
7595
188k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7596
139k
        LogFinish();
7597
7598
188k
    if (window->DC.IsSetPos)
7599
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7600
7601
    // Docking: report contents sizes to parent to allow for auto-resize
7602
188k
    if (window->DockNode && window->DockTabIsVisible)
7603
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7604
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7605
7606
    // Pop from window stack
7607
188k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7608
188k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7609
0
        g.BeginMenuCount--;
7610
188k
    if (window->Flags & ImGuiWindowFlags_Popup)
7611
0
        g.BeginPopupStack.pop_back();
7612
188k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7613
188k
    g.CurrentWindowStack.pop_back();
7614
188k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7615
188k
    if (g.CurrentWindow)
7616
118k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7617
188k
}
7618
7619
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7620
17.9k
{
7621
17.9k
    ImGuiContext& g = *GImGui;
7622
17.9k
    IM_ASSERT(window == window->RootWindow);
7623
7624
17.9k
    const int cur_order = window->FocusOrder;
7625
17.9k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7626
17.9k
    if (g.WindowsFocusOrder.back() == window)
7627
17.9k
        return;
7628
7629
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7630
0
    for (int n = cur_order; n < new_order; n++)
7631
0
    {
7632
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7633
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7634
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7635
0
    }
7636
0
    g.WindowsFocusOrder[new_order] = window;
7637
0
    window->FocusOrder = (short)new_order;
7638
0
}
7639
7640
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7641
17.9k
{
7642
17.9k
    ImGuiContext& g = *GImGui;
7643
17.9k
    ImGuiWindow* current_front_window = g.Windows.back();
7644
17.9k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7645
17.9k
        return;
7646
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7647
0
        if (g.Windows[i] == window)
7648
0
        {
7649
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7650
0
            g.Windows[g.Windows.Size - 1] = window;
7651
0
            break;
7652
0
        }
7653
0
}
7654
7655
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7656
0
{
7657
0
    ImGuiContext& g = *GImGui;
7658
0
    if (g.Windows[0] == window)
7659
0
        return;
7660
0
    for (int i = 0; i < g.Windows.Size; i++)
7661
0
        if (g.Windows[i] == window)
7662
0
        {
7663
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7664
0
            g.Windows[0] = window;
7665
0
            break;
7666
0
        }
7667
0
}
7668
7669
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7670
0
{
7671
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7672
0
    ImGuiContext& g = *GImGui;
7673
0
    window = window->RootWindow;
7674
0
    behind_window = behind_window->RootWindow;
7675
0
    int pos_wnd = FindWindowDisplayIndex(window);
7676
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7677
0
    if (pos_wnd < pos_beh)
7678
0
    {
7679
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7680
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7681
0
        g.Windows[pos_beh - 1] = window;
7682
0
    }
7683
0
    else
7684
0
    {
7685
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7686
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7687
0
        g.Windows[pos_beh] = window;
7688
0
    }
7689
0
}
7690
7691
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7692
0
{
7693
0
    ImGuiContext& g = *GImGui;
7694
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7695
0
}
7696
7697
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7698
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7699
27.3k
{
7700
27.3k
    ImGuiContext& g = *GImGui;
7701
7702
    // Modal check?
7703
27.3k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7704
178
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7705
0
        {
7706
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7707
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7708
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7709
0
            return;
7710
0
        }
7711
7712
    // Find last focused child (if any) and focus it instead.
7713
27.3k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7714
1
        window = NavRestoreLastChildNavWindow(window);
7715
7716
    // Apply focus
7717
27.3k
    if (g.NavWindow != window)
7718
11.1k
    {
7719
11.1k
        SetNavWindow(window);
7720
11.1k
        if (window && g.NavDisableMouseHover)
7721
2.19k
            g.NavMousePosDirty = true;
7722
11.1k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7723
11.1k
        g.NavLayer = ImGuiNavLayer_Main;
7724
11.1k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7725
11.1k
        g.NavIdIsAlive = false;
7726
11.1k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7727
7728
        // Close popups if any
7729
11.1k
        ClosePopupsOverWindow(window, false);
7730
11.1k
    }
7731
7732
    // Move the root window to the top of the pile
7733
27.3k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7734
27.3k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7735
27.3k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7736
27.3k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7737
27.3k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7738
7739
    // Steal active widgets. Some of the cases it triggers includes:
7740
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7741
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7742
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7743
27.3k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7744
162
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7745
66
            ClearActiveID();
7746
7747
    // Passing NULL allow to disable keyboard focus
7748
27.3k
    if (!window)
7749
9.40k
        return;
7750
17.9k
    window->LastFrameJustFocused = g.FrameCount;
7751
7752
    // Select in dock node
7753
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7754
    //if (dock_node && dock_node->TabBar)
7755
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7756
7757
    // Bring to front
7758
17.9k
    BringWindowToFocusFront(focus_front_window);
7759
17.9k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7760
17.9k
        BringWindowToDisplayFront(display_front_window);
7761
17.9k
}
7762
7763
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7764
1
{
7765
1
    ImGuiContext& g = *GImGui;
7766
1
    int start_idx = g.WindowsFocusOrder.Size - 1;
7767
1
    if (under_this_window != NULL)
7768
0
    {
7769
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7770
0
        int offset = -1;
7771
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7772
0
        {
7773
0
            under_this_window = under_this_window->ParentWindow;
7774
0
            offset = 0;
7775
0
        }
7776
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7777
0
    }
7778
1
    for (int i = start_idx; i >= 0; i--)
7779
1
    {
7780
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7781
1
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7782
1
        if (window == ignore_window || !window->WasActive)
7783
0
            continue;
7784
1
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7785
0
            continue;
7786
1
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7787
1
        {
7788
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7789
            // This is failing (lagging by one frame) for docked windows.
7790
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7791
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7792
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7793
1
            FocusWindow(window, flags);
7794
1
            return;
7795
1
        }
7796
1
    }
7797
0
    FocusWindow(NULL, flags);
7798
0
}
7799
7800
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7801
void ImGui::SetCurrentFont(ImFont* font)
7802
69.6k
{
7803
69.6k
    ImGuiContext& g = *GImGui;
7804
69.6k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7805
69.6k
    IM_ASSERT(font->Scale > 0.0f);
7806
69.6k
    g.Font = font;
7807
69.6k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7808
69.6k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7809
7810
69.6k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7811
69.6k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7812
69.6k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7813
69.6k
    g.DrawListSharedData.Font = g.Font;
7814
69.6k
    g.DrawListSharedData.FontSize = g.FontSize;
7815
69.6k
}
7816
7817
void ImGui::PushFont(ImFont* font)
7818
0
{
7819
0
    ImGuiContext& g = *GImGui;
7820
0
    if (!font)
7821
0
        font = GetDefaultFont();
7822
0
    SetCurrentFont(font);
7823
0
    g.FontStack.push_back(font);
7824
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7825
0
}
7826
7827
void  ImGui::PopFont()
7828
0
{
7829
0
    ImGuiContext& g = *GImGui;
7830
0
    g.CurrentWindow->DrawList->PopTextureID();
7831
0
    g.FontStack.pop_back();
7832
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7833
0
}
7834
7835
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7836
49.0k
{
7837
49.0k
    ImGuiContext& g = *GImGui;
7838
49.0k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7839
49.0k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7840
49.0k
    if (enabled)
7841
0
        item_flags |= option;
7842
49.0k
    else
7843
49.0k
        item_flags &= ~option;
7844
49.0k
    g.CurrentItemFlags = item_flags;
7845
49.0k
    g.ItemFlagsStack.push_back(item_flags);
7846
49.0k
}
7847
7848
void ImGui::PopItemFlag()
7849
49.0k
{
7850
49.0k
    ImGuiContext& g = *GImGui;
7851
49.0k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7852
49.0k
    g.ItemFlagsStack.pop_back();
7853
49.0k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7854
49.0k
}
7855
7856
// BeginDisabled()/EndDisabled()
7857
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7858
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7859
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7860
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7861
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7862
void ImGui::BeginDisabled(bool disabled)
7863
0
{
7864
0
    ImGuiContext& g = *GImGui;
7865
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7866
0
    if (!was_disabled && disabled)
7867
0
    {
7868
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7869
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7870
0
    }
7871
0
    if (was_disabled || disabled)
7872
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7873
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7874
0
    g.DisabledStackSize++;
7875
0
}
7876
7877
void ImGui::EndDisabled()
7878
0
{
7879
0
    ImGuiContext& g = *GImGui;
7880
0
    IM_ASSERT(g.DisabledStackSize > 0);
7881
0
    g.DisabledStackSize--;
7882
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7883
    //PopItemFlag();
7884
0
    g.ItemFlagsStack.pop_back();
7885
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7886
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7887
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7888
0
}
7889
7890
void ImGui::PushTabStop(bool tab_stop)
7891
49.0k
{
7892
49.0k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7893
49.0k
}
7894
7895
void ImGui::PopTabStop()
7896
49.0k
{
7897
49.0k
    PopItemFlag();
7898
49.0k
}
7899
7900
void ImGui::PushButtonRepeat(bool repeat)
7901
0
{
7902
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7903
0
}
7904
7905
void ImGui::PopButtonRepeat()
7906
0
{
7907
0
    PopItemFlag();
7908
0
}
7909
7910
void ImGui::PushTextWrapPos(float wrap_pos_x)
7911
0
{
7912
0
    ImGuiWindow* window = GetCurrentWindow();
7913
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7914
0
    window->DC.TextWrapPos = wrap_pos_x;
7915
0
}
7916
7917
void ImGui::PopTextWrapPos()
7918
0
{
7919
0
    ImGuiWindow* window = GetCurrentWindow();
7920
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7921
0
    window->DC.TextWrapPosStack.pop_back();
7922
0
}
7923
7924
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7925
0
{
7926
0
    ImGuiWindow* last_window = NULL;
7927
0
    while (last_window != window)
7928
0
    {
7929
0
        last_window = window;
7930
0
        window = window->RootWindow;
7931
0
        if (popup_hierarchy)
7932
0
            window = window->RootWindowPopupTree;
7933
0
    if (dock_hierarchy)
7934
0
      window = window->RootWindowDockTree;
7935
0
  }
7936
0
    return window;
7937
0
}
7938
7939
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7940
0
{
7941
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7942
0
    if (window_root == potential_parent)
7943
0
        return true;
7944
0
    while (window != NULL)
7945
0
    {
7946
0
        if (window == potential_parent)
7947
0
            return true;
7948
0
        if (window == window_root) // end of chain
7949
0
            return false;
7950
0
        window = window->ParentWindow;
7951
0
    }
7952
0
    return false;
7953
0
}
7954
7955
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7956
0
{
7957
0
    if (window->RootWindow == potential_parent)
7958
0
        return true;
7959
0
    while (window != NULL)
7960
0
    {
7961
0
        if (window == potential_parent)
7962
0
            return true;
7963
0
        window = window->ParentWindowInBeginStack;
7964
0
    }
7965
0
    return false;
7966
0
}
7967
7968
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7969
0
{
7970
0
    ImGuiContext& g = *GImGui;
7971
7972
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7973
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7974
0
    if (display_layer_delta != 0)
7975
0
        return display_layer_delta > 0;
7976
7977
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7978
0
    {
7979
0
        ImGuiWindow* candidate_window = g.Windows[i];
7980
0
        if (candidate_window == potential_above)
7981
0
            return true;
7982
0
        if (candidate_window == potential_below)
7983
0
            return false;
7984
0
    }
7985
0
    return false;
7986
0
}
7987
7988
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
7989
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
7990
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
7991
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
7992
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7993
74.5k
{
7994
74.5k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
7995
7996
74.5k
    ImGuiContext& g = *GImGui;
7997
74.5k
    ImGuiWindow* ref_window = g.HoveredWindow;
7998
74.5k
    ImGuiWindow* cur_window = g.CurrentWindow;
7999
74.5k
    if (ref_window == NULL)
8000
71.8k
        return false;
8001
8002
2.70k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8003
2.70k
    {
8004
2.70k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8005
2.70k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8006
2.70k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8007
2.70k
        if (flags & ImGuiHoveredFlags_RootWindow)
8008
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8009
8010
2.70k
        bool result;
8011
2.70k
        if (flags & ImGuiHoveredFlags_ChildWindows)
8012
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8013
2.70k
        else
8014
2.70k
            result = (ref_window == cur_window);
8015
2.70k
        if (!result)
8016
2.68k
            return false;
8017
2.70k
    }
8018
8019
22
    if (!IsWindowContentHoverable(ref_window, flags))
8020
0
        return false;
8021
22
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8022
22
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8023
14
            return false;
8024
8025
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8026
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8027
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8028
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8029
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8030
8
    if (flags & ImGuiHoveredFlags_ForTooltip)
8031
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8032
8
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8033
0
        return false;
8034
8035
8
    return true;
8036
8
}
8037
8038
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8039
96.9k
{
8040
96.9k
    ImGuiContext& g = *GImGui;
8041
96.9k
    ImGuiWindow* ref_window = g.NavWindow;
8042
96.9k
    ImGuiWindow* cur_window = g.CurrentWindow;
8043
8044
96.9k
    if (ref_window == NULL)
8045
21.6k
        return false;
8046
75.3k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8047
0
        return true;
8048
8049
75.3k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8050
75.3k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8051
75.3k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8052
75.3k
    if (flags & ImGuiHoveredFlags_RootWindow)
8053
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8054
8055
75.3k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8056
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8057
75.3k
    else
8058
75.3k
        return (ref_window == cur_window);
8059
75.3k
}
8060
8061
ImGuiID ImGui::GetWindowDockID()
8062
0
{
8063
0
    ImGuiContext& g = *GImGui;
8064
0
    return g.CurrentWindow->DockId;
8065
0
}
8066
8067
bool ImGui::IsWindowDocked()
8068
0
{
8069
0
    ImGuiContext& g = *GImGui;
8070
0
    return g.CurrentWindow->DockIsActive;
8071
0
}
8072
8073
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8074
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8075
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8076
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8077
0
{
8078
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8079
0
}
8080
8081
float ImGui::GetWindowWidth()
8082
16.2k
{
8083
16.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
8084
16.2k
    return window->Size.x;
8085
16.2k
}
8086
8087
float ImGui::GetWindowHeight()
8088
16.9k
{
8089
16.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
8090
16.9k
    return window->Size.y;
8091
16.9k
}
8092
8093
ImVec2 ImGui::GetWindowPos()
8094
0
{
8095
0
    ImGuiContext& g = *GImGui;
8096
0
    ImGuiWindow* window = g.CurrentWindow;
8097
0
    return window->Pos;
8098
0
}
8099
8100
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8101
223
{
8102
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8103
223
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8104
0
        return;
8105
8106
223
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8107
223
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8108
223
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8109
8110
    // Set
8111
223
    const ImVec2 old_pos = window->Pos;
8112
223
    window->Pos = ImTrunc(pos);
8113
223
    ImVec2 offset = window->Pos - old_pos;
8114
223
    if (offset.x == 0.0f && offset.y == 0.0f)
8115
0
        return;
8116
223
    MarkIniSettingsDirty(window);
8117
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8118
223
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8119
223
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8120
223
    window->DC.IdealMaxPos += offset;
8121
223
    window->DC.CursorStartPos += offset;
8122
223
}
8123
8124
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8125
0
{
8126
0
    ImGuiWindow* window = GetCurrentWindowRead();
8127
0
    SetWindowPos(window, pos, cond);
8128
0
}
8129
8130
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8131
0
{
8132
0
    if (ImGuiWindow* window = FindWindowByName(name))
8133
0
        SetWindowPos(window, pos, cond);
8134
0
}
8135
8136
ImVec2 ImGui::GetWindowSize()
8137
0
{
8138
0
    ImGuiWindow* window = GetCurrentWindowRead();
8139
0
    return window->Size;
8140
0
}
8141
8142
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8143
118k
{
8144
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8145
118k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8146
69.6k
        return;
8147
8148
49.0k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8149
49.0k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8150
8151
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8152
49.0k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8153
17
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8154
49.0k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8155
17
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8156
8157
    // Set
8158
49.0k
    ImVec2 old_size = window->SizeFull;
8159
49.0k
    if (size.x <= 0.0f)
8160
0
        window->AutoFitOnlyGrows = false;
8161
49.0k
    else
8162
49.0k
        window->SizeFull.x = IM_TRUNC(size.x);
8163
49.0k
    if (size.y <= 0.0f)
8164
0
        window->AutoFitOnlyGrows = false;
8165
49.0k
    else
8166
49.0k
        window->SizeFull.y = IM_TRUNC(size.y);
8167
49.0k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8168
47.6k
        MarkIniSettingsDirty(window);
8169
49.0k
}
8170
8171
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8172
0
{
8173
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8174
0
}
8175
8176
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8177
0
{
8178
0
    if (ImGuiWindow* window = FindWindowByName(name))
8179
0
        SetWindowSize(window, size, cond);
8180
0
}
8181
8182
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8183
0
{
8184
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8185
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8186
0
        return;
8187
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8188
8189
    // Set
8190
0
    window->Collapsed = collapsed;
8191
0
}
8192
8193
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8194
0
{
8195
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8196
0
    window->HitTestHoleSize = ImVec2ih(size);
8197
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8198
0
}
8199
8200
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8201
0
{
8202
0
    window->Hidden = window->SkipItems = true;
8203
0
    window->HiddenFramesCanSkipItems = 1;
8204
0
}
8205
8206
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8207
0
{
8208
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8209
0
}
8210
8211
bool ImGui::IsWindowCollapsed()
8212
0
{
8213
0
    ImGuiWindow* window = GetCurrentWindowRead();
8214
0
    return window->Collapsed;
8215
0
}
8216
8217
bool ImGui::IsWindowAppearing()
8218
0
{
8219
0
    ImGuiWindow* window = GetCurrentWindowRead();
8220
0
    return window->Appearing;
8221
0
}
8222
8223
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8224
0
{
8225
0
    if (ImGuiWindow* window = FindWindowByName(name))
8226
0
        SetWindowCollapsed(window, collapsed, cond);
8227
0
}
8228
8229
void ImGui::SetWindowFocus()
8230
16.2k
{
8231
16.2k
    FocusWindow(GImGui->CurrentWindow);
8232
16.2k
}
8233
8234
void ImGui::SetWindowFocus(const char* name)
8235
0
{
8236
0
    if (name)
8237
0
    {
8238
0
        if (ImGuiWindow* window = FindWindowByName(name))
8239
0
            FocusWindow(window);
8240
0
    }
8241
0
    else
8242
0
    {
8243
0
        FocusWindow(NULL);
8244
0
    }
8245
0
}
8246
8247
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8248
0
{
8249
0
    ImGuiContext& g = *GImGui;
8250
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8251
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8252
0
    g.NextWindowData.PosVal = pos;
8253
0
    g.NextWindowData.PosPivotVal = pivot;
8254
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8255
0
    g.NextWindowData.PosUndock = true;
8256
0
}
8257
8258
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8259
118k
{
8260
118k
    ImGuiContext& g = *GImGui;
8261
118k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8262
118k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8263
118k
    g.NextWindowData.SizeVal = size;
8264
118k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8265
118k
}
8266
8267
// For each axis:
8268
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8269
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8270
// - See "Demo->Examples->Constrained-resizing window" for examples.
8271
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8272
0
{
8273
0
    ImGuiContext& g = *GImGui;
8274
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8275
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8276
0
    g.NextWindowData.SizeCallback = custom_callback;
8277
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8278
0
}
8279
8280
// Content size = inner scrollable rectangle, padded with WindowPadding.
8281
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8282
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8283
0
{
8284
0
    ImGuiContext& g = *GImGui;
8285
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8286
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8287
0
}
8288
8289
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8290
0
{
8291
0
    ImGuiContext& g = *GImGui;
8292
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8293
0
    g.NextWindowData.ScrollVal = scroll;
8294
0
}
8295
8296
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8297
0
{
8298
0
    ImGuiContext& g = *GImGui;
8299
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8300
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8301
0
    g.NextWindowData.CollapsedVal = collapsed;
8302
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8303
0
}
8304
8305
void ImGui::SetNextWindowFocus()
8306
0
{
8307
0
    ImGuiContext& g = *GImGui;
8308
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8309
0
}
8310
8311
void ImGui::SetNextWindowBgAlpha(float alpha)
8312
0
{
8313
0
    ImGuiContext& g = *GImGui;
8314
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8315
0
    g.NextWindowData.BgAlphaVal = alpha;
8316
0
}
8317
8318
void ImGui::SetNextWindowViewport(ImGuiID id)
8319
0
{
8320
0
    ImGuiContext& g = *GImGui;
8321
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8322
0
    g.NextWindowData.ViewportId = id;
8323
0
}
8324
8325
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8326
0
{
8327
0
    ImGuiContext& g = *GImGui;
8328
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8329
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8330
0
    g.NextWindowData.DockId = id;
8331
0
}
8332
8333
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8334
0
{
8335
0
    ImGuiContext& g = *GImGui;
8336
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8337
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8338
0
    g.NextWindowData.WindowClass = *window_class;
8339
0
}
8340
8341
ImDrawList* ImGui::GetWindowDrawList()
8342
49.0k
{
8343
49.0k
    ImGuiWindow* window = GetCurrentWindow();
8344
49.0k
    return window->DrawList;
8345
49.0k
}
8346
8347
float ImGui::GetWindowDpiScale()
8348
0
{
8349
0
    ImGuiContext& g = *GImGui;
8350
0
    return g.CurrentDpiScale;
8351
0
}
8352
8353
ImGuiViewport* ImGui::GetWindowViewport()
8354
0
{
8355
0
    ImGuiContext& g = *GImGui;
8356
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8357
0
    return g.CurrentViewport;
8358
0
}
8359
8360
ImFont* ImGui::GetFont()
8361
96.3M
{
8362
96.3M
    return GImGui->Font;
8363
96.3M
}
8364
8365
float ImGui::GetFontSize()
8366
96.3M
{
8367
96.3M
    return GImGui->FontSize;
8368
96.3M
}
8369
8370
ImVec2 ImGui::GetFontTexUvWhitePixel()
8371
0
{
8372
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8373
0
}
8374
8375
void ImGui::SetWindowFontScale(float scale)
8376
0
{
8377
0
    IM_ASSERT(scale > 0.0f);
8378
0
    ImGuiContext& g = *GImGui;
8379
0
    ImGuiWindow* window = GetCurrentWindow();
8380
0
    window->FontWindowScale = scale;
8381
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8382
0
}
8383
8384
void ImGui::PushFocusScope(ImGuiID id)
8385
188k
{
8386
188k
    ImGuiContext& g = *GImGui;
8387
188k
    g.FocusScopeStack.push_back(id);
8388
188k
    g.CurrentFocusScopeId = id;
8389
188k
}
8390
8391
void ImGui::PopFocusScope()
8392
188k
{
8393
188k
    ImGuiContext& g = *GImGui;
8394
188k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8395
188k
    g.FocusScopeStack.pop_back();
8396
188k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8397
188k
}
8398
8399
// Focus = move navigation cursor, set scrolling, set focus window.
8400
void ImGui::FocusItem()
8401
0
{
8402
0
    ImGuiContext& g = *GImGui;
8403
0
    ImGuiWindow* window = g.CurrentWindow;
8404
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8405
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8406
0
    {
8407
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8408
0
        return;
8409
0
    }
8410
8411
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8412
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8413
0
    SetNavWindow(window);
8414
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8415
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8416
0
}
8417
8418
void ImGui::ActivateItemByID(ImGuiID id)
8419
0
{
8420
0
    ImGuiContext& g = *GImGui;
8421
0
    g.NavNextActivateId = id;
8422
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8423
0
}
8424
8425
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8426
// But ActivateItem() should function without altering scroll/focus?
8427
void ImGui::SetKeyboardFocusHere(int offset)
8428
0
{
8429
0
    ImGuiContext& g = *GImGui;
8430
0
    ImGuiWindow* window = g.CurrentWindow;
8431
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8432
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8433
8434
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8435
    // When we refactor this function into ActivateItem() we may want to make this an option.
8436
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8437
    // is also automatically dropped in the event g.ActiveId is stolen.
8438
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8439
0
    {
8440
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8441
0
        return;
8442
0
    }
8443
8444
0
    SetNavWindow(window);
8445
8446
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8447
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8448
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8449
0
    if (offset == -1)
8450
0
    {
8451
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8452
0
    }
8453
0
    else
8454
0
    {
8455
0
        g.NavTabbingDir = 1;
8456
0
        g.NavTabbingCounter = offset + 1;
8457
0
    }
8458
0
}
8459
8460
void ImGui::SetItemDefaultFocus()
8461
0
{
8462
0
    ImGuiContext& g = *GImGui;
8463
0
    ImGuiWindow* window = g.CurrentWindow;
8464
0
    if (!window->Appearing)
8465
0
        return;
8466
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8467
0
        return;
8468
8469
0
    g.NavInitRequest = false;
8470
0
    NavApplyItemToResult(&g.NavInitResult);
8471
0
    NavUpdateAnyRequestFlag();
8472
8473
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8474
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8475
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8476
0
}
8477
8478
void ImGui::SetStateStorage(ImGuiStorage* tree)
8479
0
{
8480
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8481
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8482
0
}
8483
8484
ImGuiStorage* ImGui::GetStateStorage()
8485
0
{
8486
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8487
0
    return window->DC.StateStorage;
8488
0
}
8489
8490
void ImGui::PushID(const char* str_id)
8491
49.0k
{
8492
49.0k
    ImGuiContext& g = *GImGui;
8493
49.0k
    ImGuiWindow* window = g.CurrentWindow;
8494
49.0k
    ImGuiID id = window->GetID(str_id);
8495
49.0k
    window->IDStack.push_back(id);
8496
49.0k
}
8497
8498
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8499
0
{
8500
0
    ImGuiContext& g = *GImGui;
8501
0
    ImGuiWindow* window = g.CurrentWindow;
8502
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8503
0
    window->IDStack.push_back(id);
8504
0
}
8505
8506
void ImGui::PushID(const void* ptr_id)
8507
0
{
8508
0
    ImGuiContext& g = *GImGui;
8509
0
    ImGuiWindow* window = g.CurrentWindow;
8510
0
    ImGuiID id = window->GetID(ptr_id);
8511
0
    window->IDStack.push_back(id);
8512
0
}
8513
8514
void ImGui::PushID(int int_id)
8515
0
{
8516
0
    ImGuiContext& g = *GImGui;
8517
0
    ImGuiWindow* window = g.CurrentWindow;
8518
0
    ImGuiID id = window->GetID(int_id);
8519
0
    window->IDStack.push_back(id);
8520
0
}
8521
8522
// Push a given id value ignoring the ID stack as a seed.
8523
void ImGui::PushOverrideID(ImGuiID id)
8524
0
{
8525
0
    ImGuiContext& g = *GImGui;
8526
0
    ImGuiWindow* window = g.CurrentWindow;
8527
0
    if (g.DebugHookIdInfo == id)
8528
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8529
0
    window->IDStack.push_back(id);
8530
0
}
8531
8532
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8533
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8534
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8535
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8536
0
{
8537
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8538
0
    ImGuiContext& g = *GImGui;
8539
0
    if (g.DebugHookIdInfo == id)
8540
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8541
0
    return id;
8542
0
}
8543
8544
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8545
0
{
8546
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8547
0
    ImGuiContext& g = *GImGui;
8548
0
    if (g.DebugHookIdInfo == id)
8549
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8550
0
    return id;
8551
0
}
8552
8553
void ImGui::PopID()
8554
49.0k
{
8555
49.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
8556
49.0k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8557
49.0k
    window->IDStack.pop_back();
8558
49.0k
}
8559
8560
ImGuiID ImGui::GetID(const char* str_id)
8561
0
{
8562
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8563
0
    return window->GetID(str_id);
8564
0
}
8565
8566
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8567
0
{
8568
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8569
0
    return window->GetID(str_id_begin, str_id_end);
8570
0
}
8571
8572
ImGuiID ImGui::GetID(const void* ptr_id)
8573
0
{
8574
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8575
0
    return window->GetID(ptr_id);
8576
0
}
8577
8578
bool ImGui::IsRectVisible(const ImVec2& size)
8579
0
{
8580
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8581
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8582
0
}
8583
8584
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8585
0
{
8586
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8587
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8588
0
}
8589
8590
8591
//-----------------------------------------------------------------------------
8592
// [SECTION] INPUTS
8593
//-----------------------------------------------------------------------------
8594
// - GetKeyData() [Internal]
8595
// - GetKeyIndex() [Internal]
8596
// - GetKeyName()
8597
// - GetKeyChordName() [Internal]
8598
// - CalcTypematicRepeatAmount() [Internal]
8599
// - GetTypematicRepeatRate() [Internal]
8600
// - GetKeyPressedAmount() [Internal]
8601
// - GetKeyMagnitude2d() [Internal]
8602
//-----------------------------------------------------------------------------
8603
// - UpdateKeyRoutingTable() [Internal]
8604
// - GetRoutingIdFromOwnerId() [Internal]
8605
// - GetShortcutRoutingData() [Internal]
8606
// - CalcRoutingScore() [Internal]
8607
// - SetShortcutRouting() [Internal]
8608
// - TestShortcutRouting() [Internal]
8609
//-----------------------------------------------------------------------------
8610
// - IsKeyDown()
8611
// - IsKeyPressed()
8612
// - IsKeyReleased()
8613
//-----------------------------------------------------------------------------
8614
// - IsMouseDown()
8615
// - IsMouseClicked()
8616
// - IsMouseReleased()
8617
// - IsMouseDoubleClicked()
8618
// - GetMouseClickedCount()
8619
// - IsMouseHoveringRect() [Internal]
8620
// - IsMouseDragPastThreshold() [Internal]
8621
// - IsMouseDragging()
8622
// - GetMousePos()
8623
// - SetMousePos() [Internal]
8624
// - GetMousePosOnOpeningCurrentPopup()
8625
// - IsMousePosValid()
8626
// - IsAnyMouseDown()
8627
// - GetMouseDragDelta()
8628
// - ResetMouseDragDelta()
8629
// - GetMouseCursor()
8630
// - SetMouseCursor()
8631
//-----------------------------------------------------------------------------
8632
// - UpdateAliasKey()
8633
// - GetMergedModsFromKeys()
8634
// - UpdateKeyboardInputs()
8635
// - UpdateMouseInputs()
8636
//-----------------------------------------------------------------------------
8637
// - LockWheelingWindow [Internal]
8638
// - FindBestWheelingWindow [Internal]
8639
// - UpdateMouseWheel() [Internal]
8640
//-----------------------------------------------------------------------------
8641
// - SetNextFrameWantCaptureKeyboard()
8642
// - SetNextFrameWantCaptureMouse()
8643
//-----------------------------------------------------------------------------
8644
// - GetInputSourceName() [Internal]
8645
// - DebugPrintInputEvent() [Internal]
8646
// - UpdateInputEvents() [Internal]
8647
//-----------------------------------------------------------------------------
8648
// - GetKeyOwner() [Internal]
8649
// - TestKeyOwner() [Internal]
8650
// - SetKeyOwner() [Internal]
8651
// - SetItemKeyOwner() [Internal]
8652
// - Shortcut() [Internal]
8653
//-----------------------------------------------------------------------------
8654
8655
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8656
2.42M
{
8657
2.42M
    ImGuiContext& g = *ctx;
8658
8659
    // Special storage location for mods
8660
2.42M
    if (key & ImGuiMod_Mask_)
8661
627k
        key = ConvertSingleModFlagToKey(ctx, key);
8662
8663
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8664
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8665
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8666
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8667
#else
8668
2.42M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8669
2.42M
#endif
8670
2.42M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8671
2.42M
}
8672
8673
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8674
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8675
{
8676
    ImGuiContext& g = *GImGui;
8677
    IM_ASSERT(IsNamedKey(key));
8678
    const ImGuiKeyData* key_data = GetKeyData(key);
8679
    return (ImGuiKey)(key_data - g.IO.KeysData);
8680
}
8681
#endif
8682
8683
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8684
static const char* const GKeyNames[] =
8685
{
8686
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8687
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8688
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8689
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8690
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8691
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8692
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8693
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8694
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8695
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8696
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8697
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8698
    "AppBack", "AppForward",
8699
    "GamepadStart", "GamepadBack",
8700
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8701
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8702
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8703
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8704
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8705
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8706
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8707
};
8708
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8709
8710
const char* ImGui::GetKeyName(ImGuiKey key)
8711
0
{
8712
0
    ImGuiContext& g = *GImGui;
8713
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8714
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8715
#else
8716
    if (IsLegacyKey(key))
8717
    {
8718
        if (g.IO.KeyMap[key] == -1)
8719
            return "N/A";
8720
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8721
        key = (ImGuiKey)g.IO.KeyMap[key];
8722
    }
8723
#endif
8724
0
    if (key == ImGuiKey_None)
8725
0
        return "None";
8726
0
    if (key & ImGuiMod_Mask_)
8727
0
        key = ConvertSingleModFlagToKey(&g, key);
8728
0
    if (!IsNamedKey(key))
8729
0
        return "Unknown";
8730
8731
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8732
0
}
8733
8734
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8735
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8736
0
{
8737
0
    ImGuiContext& g = *GImGui;
8738
0
    if (key_chord & ImGuiMod_Shortcut)
8739
0
        key_chord = ConvertShortcutMod(key_chord);
8740
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8741
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8742
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8743
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8744
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8745
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8746
0
}
8747
8748
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8749
// t1 = current time (e.g.: g.Time)
8750
// An event is triggered at:
8751
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8752
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8753
14.3k
{
8754
14.3k
    if (t1 == 0.0f)
8755
0
        return 1;
8756
14.3k
    if (t0 >= t1)
8757
0
        return 0;
8758
14.3k
    if (repeat_rate <= 0.0f)
8759
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8760
14.3k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8761
14.3k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8762
14.3k
    const int count = count_t1 - count_t0;
8763
14.3k
    return count;
8764
14.3k
}
8765
8766
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8767
30.0k
{
8768
30.0k
    ImGuiContext& g = *GImGui;
8769
30.0k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8770
30.0k
    {
8771
6.89k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8772
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8773
23.1k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8774
30.0k
    }
8775
30.0k
}
8776
8777
// Return value representing the number of presses in the last time period, for the given repeat rate
8778
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8779
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8780
14.3k
{
8781
14.3k
    ImGuiContext& g = *GImGui;
8782
14.3k
    const ImGuiKeyData* key_data = GetKeyData(key);
8783
14.3k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8784
0
        return 0;
8785
14.3k
    const float t = key_data->DownDuration;
8786
14.3k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8787
14.3k
}
8788
8789
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8790
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8791
0
{
8792
0
    return ImVec2(
8793
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8794
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8795
0
}
8796
8797
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8798
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8799
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8800
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8801
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8802
69.6k
{
8803
69.6k
    ImGuiContext& g = *GImGui;
8804
69.6k
    rt->EntriesNext.resize(0);
8805
10.8M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8806
10.7M
    {
8807
10.7M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8808
10.7M
        ImGuiKeyRoutingData* routing_entry;
8809
10.7M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8810
0
        {
8811
0
            routing_entry = &rt->Entries[old_routing_idx];
8812
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8813
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8814
0
            routing_entry->RoutingNextScore = 255;
8815
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8816
0
                continue;
8817
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8818
8819
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8820
0
            if (routing_entry->Mods == g.IO.KeyMods)
8821
0
            {
8822
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8823
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8824
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8825
0
            }
8826
0
        }
8827
8828
        // Rewrite linked-list
8829
10.7M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8830
10.7M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8831
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8832
10.7M
    }
8833
69.6k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8834
69.6k
}
8835
8836
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8837
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8838
0
{
8839
0
    ImGuiContext& g = *GImGui;
8840
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8841
0
}
8842
8843
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8844
0
{
8845
    // Majority of shortcuts will be Key + any number of Mods
8846
    // We accept _Single_ mod with ImGuiKey_None.
8847
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8848
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8849
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8850
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8851
0
    ImGuiContext& g = *GImGui;
8852
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8853
0
    ImGuiKeyRoutingData* routing_data;
8854
0
    if (key_chord & ImGuiMod_Shortcut)
8855
0
        key_chord = ConvertShortcutMod(key_chord);
8856
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8857
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8858
0
    if (key == ImGuiKey_None)
8859
0
        key = ConvertSingleModFlagToKey(&g, mods);
8860
0
    IM_ASSERT(IsNamedKey(key));
8861
8862
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8863
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8864
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8865
0
    {
8866
0
        routing_data = &rt->Entries[idx];
8867
0
        if (routing_data->Mods == mods)
8868
0
            return routing_data;
8869
0
    }
8870
8871
    // Add to linked-list
8872
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8873
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8874
0
    routing_data = &rt->Entries[routing_data_idx];
8875
0
    routing_data->Mods = (ImU16)mods;
8876
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8877
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8878
0
    return routing_data;
8879
0
}
8880
8881
// Current score encoding (lower is highest priority):
8882
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8883
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8884
//  -   2: ImGuiInputFlags_RouteGlobal
8885
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8886
//  - 254: ImGuiInputFlags_RouteGlobalLow
8887
//  - 255: never route
8888
// 'flags' should include an explicit routing policy
8889
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8890
0
{
8891
0
    if (flags & ImGuiInputFlags_RouteFocused)
8892
0
    {
8893
0
        ImGuiContext& g = *GImGui;
8894
0
        ImGuiWindow* focused = g.NavWindow;
8895
8896
        // ActiveID gets top priority
8897
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8898
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8899
0
            return 1;
8900
8901
        // Early out when not in focus stack
8902
0
        if (focused == NULL || focused->RootWindow != location->RootWindow)
8903
0
            return 255;
8904
8905
        // Score based on distance to focused window (lower is better)
8906
        // Assuming both windows are submitting a routing request,
8907
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8908
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8909
        // Assuming only WindowA is submitting a routing request,
8910
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8911
0
        for (int next_score = 3; focused != NULL; next_score++)
8912
0
        {
8913
0
            if (focused == location)
8914
0
            {
8915
0
                IM_ASSERT(next_score < 255);
8916
0
                return next_score;
8917
0
            }
8918
0
            focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8919
0
        }
8920
0
        return 255;
8921
0
    }
8922
8923
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8924
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8925
0
        return 2;
8926
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8927
0
        return 254;
8928
0
    return 0;
8929
0
}
8930
8931
// Request a desired route for an input chord (key + mods).
8932
// Return true if the route is available this frame.
8933
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8934
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8935
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8936
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8937
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8938
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8939
139k
{
8940
139k
    ImGuiContext& g = *GImGui;
8941
139k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8942
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8943
139k
    else
8944
139k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8945
8946
139k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8947
0
        if (g.NavWindow == NULL)
8948
0
            return false;
8949
139k
    if (flags & ImGuiInputFlags_RouteAlways)
8950
139k
        return true;
8951
8952
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8953
0
    if (score == 255)
8954
0
        return false;
8955
8956
    // Submit routing for NEXT frame (assuming score is sufficient)
8957
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8958
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8959
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8960
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8961
0
    if (score < routing_data->RoutingNextScore)
8962
0
    {
8963
0
        routing_data->RoutingNext = routing_id;
8964
0
        routing_data->RoutingNextScore = (ImU8)score;
8965
0
    }
8966
8967
    // Return routing state for CURRENT frame
8968
0
    return routing_data->RoutingCurr == routing_id;
8969
0
}
8970
8971
// Currently unused by core (but used by tests)
8972
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8973
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8974
0
{
8975
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8976
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8977
0
    return routing_data->RoutingCurr == routing_id;
8978
0
}
8979
8980
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8981
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8982
bool ImGui::IsKeyDown(ImGuiKey key)
8983
1.07M
{
8984
1.07M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8985
1.07M
}
8986
8987
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8988
1.15M
{
8989
1.15M
    const ImGuiKeyData* key_data = GetKeyData(key);
8990
1.15M
    if (!key_data->Down)
8991
1.11M
        return false;
8992
41.9k
    if (!TestKeyOwner(key, owner_id))
8993
4
        return false;
8994
41.9k
    return true;
8995
41.9k
}
8996
8997
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8998
351k
{
8999
351k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9000
351k
}
9001
9002
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9003
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9004
757k
{
9005
757k
    const ImGuiKeyData* key_data = GetKeyData(key);
9006
757k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9007
709k
        return false;
9008
48.4k
    const float t = key_data->DownDuration;
9009
48.4k
    if (t < 0.0f)
9010
0
        return false;
9011
48.4k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9012
9013
48.4k
    bool pressed = (t == 0.0f);
9014
48.4k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
9015
30.0k
    {
9016
30.0k
        float repeat_delay, repeat_rate;
9017
30.0k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9018
30.0k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9019
30.0k
    }
9020
48.4k
    if (!pressed)
9021
40.8k
        return false;
9022
7.60k
    if (!TestKeyOwner(key, owner_id))
9023
4
        return false;
9024
7.60k
    return true;
9025
7.60k
}
9026
9027
bool ImGui::IsKeyReleased(ImGuiKey key)
9028
0
{
9029
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9030
0
}
9031
9032
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9033
0
{
9034
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9035
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9036
0
        return false;
9037
0
    if (!TestKeyOwner(key, owner_id))
9038
0
        return false;
9039
0
    return true;
9040
0
}
9041
9042
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9043
0
{
9044
0
    ImGuiContext& g = *GImGui;
9045
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9046
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9047
0
}
9048
9049
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9050
896
{
9051
896
    ImGuiContext& g = *GImGui;
9052
896
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9053
896
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9054
896
}
9055
9056
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9057
107
{
9058
107
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9059
107
}
9060
9061
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9062
1.55k
{
9063
1.55k
    ImGuiContext& g = *GImGui;
9064
1.55k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9065
1.55k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9066
686
        return false;
9067
872
    const float t = g.IO.MouseDownDuration[button];
9068
872
    if (t < 0.0f)
9069
0
        return false;
9070
872
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9071
9072
872
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9073
872
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9074
872
    if (!pressed)
9075
689
        return false;
9076
9077
183
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9078
0
        return false;
9079
9080
183
    return true;
9081
183
}
9082
9083
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9084
0
{
9085
0
    ImGuiContext& g = *GImGui;
9086
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9087
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9088
0
}
9089
9090
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9091
1.45k
{
9092
1.45k
    ImGuiContext& g = *GImGui;
9093
1.45k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9094
1.45k
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9095
1.45k
}
9096
9097
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9098
8
{
9099
8
    ImGuiContext& g = *GImGui;
9100
8
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9101
8
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9102
8
}
9103
9104
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9105
0
{
9106
0
    ImGuiContext& g = *GImGui;
9107
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9108
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9109
0
}
9110
9111
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9112
0
{
9113
0
    ImGuiContext& g = *GImGui;
9114
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9115
0
    return g.IO.MouseClickedCount[button];
9116
0
}
9117
9118
// Test if mouse cursor is hovering given rectangle
9119
// NB- Rectangle is clipped by our current clip setting
9120
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9121
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9122
396k
{
9123
396k
    ImGuiContext& g = *GImGui;
9124
9125
    // Clip
9126
396k
    ImRect rect_clipped(r_min, r_max);
9127
396k
    if (clip)
9128
208k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9129
9130
    // Hit testing, expanded for touch input
9131
396k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9132
387k
        return false;
9133
9.39k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9134
0
        return false;
9135
9.39k
    return true;
9136
9.39k
}
9137
9138
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9139
// [Internal] This doesn't test if the button is pressed
9140
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9141
1.53k
{
9142
1.53k
    ImGuiContext& g = *GImGui;
9143
1.53k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9144
1.53k
    if (lock_threshold < 0.0f)
9145
1.53k
        lock_threshold = g.IO.MouseDragThreshold;
9146
1.53k
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9147
1.53k
}
9148
9149
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9150
1.53k
{
9151
1.53k
    ImGuiContext& g = *GImGui;
9152
1.53k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9153
1.53k
    if (!g.IO.MouseDown[button])
9154
2
        return false;
9155
1.53k
    return IsMouseDragPastThreshold(button, lock_threshold);
9156
1.53k
}
9157
9158
ImVec2 ImGui::GetMousePos()
9159
8.27k
{
9160
8.27k
    ImGuiContext& g = *GImGui;
9161
8.27k
    return g.IO.MousePos;
9162
8.27k
}
9163
9164
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9165
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9166
void ImGui::TeleportMousePos(const ImVec2& pos)
9167
0
{
9168
0
    ImGuiContext& g = *GImGui;
9169
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9170
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9171
0
    g.IO.WantSetMousePos = true;
9172
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9173
0
}
9174
9175
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9176
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9177
0
{
9178
0
    ImGuiContext& g = *GImGui;
9179
0
    if (g.BeginPopupStack.Size > 0)
9180
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9181
0
    return g.IO.MousePos;
9182
0
}
9183
9184
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9185
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9186
218k
{
9187
    // The assert is only to silence a false-positive in XCode Static Analysis.
9188
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9189
218k
    IM_ASSERT(GImGui != NULL);
9190
218k
    const float MOUSE_INVALID = -256000.0f;
9191
218k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9192
218k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9193
218k
}
9194
9195
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9196
bool ImGui::IsAnyMouseDown()
9197
0
{
9198
0
    ImGuiContext& g = *GImGui;
9199
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9200
0
        if (g.IO.MouseDown[n])
9201
0
            return true;
9202
0
    return false;
9203
0
}
9204
9205
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9206
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9207
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9208
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9209
0
{
9210
0
    ImGuiContext& g = *GImGui;
9211
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9212
0
    if (lock_threshold < 0.0f)
9213
0
        lock_threshold = g.IO.MouseDragThreshold;
9214
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9215
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9216
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9217
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9218
0
    return ImVec2(0.0f, 0.0f);
9219
0
}
9220
9221
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9222
0
{
9223
0
    ImGuiContext& g = *GImGui;
9224
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9225
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9226
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9227
0
}
9228
9229
// Get desired mouse cursor shape.
9230
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9231
// updated during the frame, and locked in EndFrame()/Render().
9232
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9233
ImGuiMouseCursor ImGui::GetMouseCursor()
9234
0
{
9235
0
    ImGuiContext& g = *GImGui;
9236
0
    return g.MouseCursor;
9237
0
}
9238
9239
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9240
0
{
9241
0
    ImGuiContext& g = *GImGui;
9242
0
    g.MouseCursor = cursor_type;
9243
0
}
9244
9245
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9246
487k
{
9247
487k
    IM_ASSERT(ImGui::IsAliasKey(key));
9248
487k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9249
487k
    key_data->Down = v;
9250
487k
    key_data->AnalogValue = analog_value;
9251
487k
}
9252
9253
// [Internal] Do not use directly
9254
static ImGuiKeyChord GetMergedModsFromKeys()
9255
139k
{
9256
139k
    ImGuiKeyChord mods = 0;
9257
139k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9258
139k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9259
139k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9260
139k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9261
139k
    return mods;
9262
139k
}
9263
9264
static void ImGui::UpdateKeyboardInputs()
9265
69.6k
{
9266
69.6k
    ImGuiContext& g = *GImGui;
9267
69.6k
    ImGuiIO& io = g.IO;
9268
9269
    // Import legacy keys or verify they are not used
9270
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9271
    if (io.BackendUsingLegacyKeyArrays == 0)
9272
    {
9273
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9274
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9275
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9276
    }
9277
    else
9278
    {
9279
        if (g.FrameCount == 0)
9280
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9281
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9282
9283
        // Build reverse KeyMap (Named -> Legacy)
9284
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9285
            if (io.KeyMap[n] != -1)
9286
            {
9287
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9288
                io.KeyMap[io.KeyMap[n]] = n;
9289
            }
9290
9291
        // Import legacy keys into new ones
9292
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9293
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9294
            {
9295
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9296
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9297
                io.KeysData[key].Down = io.KeysDown[n];
9298
                if (key != n)
9299
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9300
                io.BackendUsingLegacyKeyArrays = 1;
9301
            }
9302
        if (io.BackendUsingLegacyKeyArrays == 1)
9303
        {
9304
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9305
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9306
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9307
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9308
        }
9309
    }
9310
9311
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9312
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9313
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9314
    {
9315
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9316
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9317
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9318
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9319
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9320
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9321
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9322
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9323
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9324
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9325
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9326
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9327
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9328
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9329
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9330
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9331
        #undef NAV_MAP_KEY
9332
    }
9333
#endif
9334
#endif
9335
9336
    // Update aliases
9337
418k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9338
348k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9339
69.6k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9340
69.6k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9341
9342
    // Synchronize io.KeyMods and io.KeyXXX values.
9343
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9344
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9345
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9346
69.6k
    io.KeyMods = GetMergedModsFromKeys();
9347
69.6k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9348
69.6k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9349
69.6k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9350
69.6k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9351
9352
    // Clear gamepad data if disabled
9353
69.6k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9354
1.74M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9355
1.67M
        {
9356
1.67M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9357
1.67M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9358
1.67M
        }
9359
9360
    // Update keys
9361
10.8M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9362
10.7M
    {
9363
10.7M
        ImGuiKeyData* key_data = &io.KeysData[i];
9364
10.7M
        key_data->DownDurationPrev = key_data->DownDuration;
9365
10.7M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9366
10.7M
    }
9367
9368
    // Update keys/input owner (named keys only): one entry per key
9369
10.8M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9370
10.7M
    {
9371
10.7M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9372
10.7M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9373
10.7M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9374
10.7M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9375
10.6M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9376
10.7M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9377
10.7M
    }
9378
9379
69.6k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9380
69.6k
}
9381
9382
static void ImGui::UpdateMouseInputs()
9383
69.6k
{
9384
69.6k
    ImGuiContext& g = *GImGui;
9385
69.6k
    ImGuiIO& io = g.IO;
9386
9387
    // Mouse Wheel swapping flag
9388
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9389
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9390
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9391
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9392
69.6k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9393
9394
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9395
69.6k
    if (IsMousePosValid(&io.MousePos))
9396
12.4k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9397
9398
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9399
69.6k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9400
11.5k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9401
58.1k
    else
9402
58.1k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9403
9404
    // Update stationary timer.
9405
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9406
69.6k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9407
69.6k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9408
69.6k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9409
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9410
9411
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9412
69.6k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9413
953
        g.NavDisableMouseHover = false;
9414
9415
418k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9416
348k
    {
9417
348k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9418
348k
        io.MouseClickedCount[i] = 0; // Will be filled below
9419
348k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9420
348k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9421
348k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9422
348k
        if (io.MouseClicked[i])
9423
2.25k
        {
9424
2.25k
            bool is_repeated_click = false;
9425
2.25k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9426
1.31k
            {
9427
1.31k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9428
1.31k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9429
1.06k
                    is_repeated_click = true;
9430
1.31k
            }
9431
2.25k
            if (is_repeated_click)
9432
1.06k
                io.MouseClickedLastCount[i]++;
9433
1.18k
            else
9434
1.18k
                io.MouseClickedLastCount[i] = 1;
9435
2.25k
            io.MouseClickedTime[i] = g.Time;
9436
2.25k
            io.MouseClickedPos[i] = io.MousePos;
9437
2.25k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9438
2.25k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9439
2.25k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9440
2.25k
        }
9441
346k
        else if (io.MouseDown[i])
9442
15.6k
        {
9443
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9444
15.6k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9445
15.6k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9446
15.6k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9447
15.6k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9448
15.6k
        }
9449
9450
        // We provide io.MouseDoubleClicked[] as a legacy service
9451
348k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9452
9453
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9454
348k
        if (io.MouseClicked[i])
9455
2.25k
            g.NavDisableMouseHover = false;
9456
348k
    }
9457
69.6k
}
9458
9459
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9460
20
{
9461
20
    ImGuiContext& g = *GImGui;
9462
20
    if (window)
9463
10
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9464
10
    else
9465
10
        g.WheelingWindowReleaseTimer = 0.0f;
9466
20
    if (g.WheelingWindow == window)
9467
0
        return;
9468
20
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9469
20
    g.WheelingWindow = window;
9470
20
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9471
20
    if (window == NULL)
9472
10
    {
9473
10
        g.WheelingWindowStartFrame = -1;
9474
10
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9475
10
    }
9476
20
}
9477
9478
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9479
30
{
9480
    // For each axis, find window in the hierarchy that may want to use scrolling
9481
30
    ImGuiContext& g = *GImGui;
9482
30
    ImGuiWindow* windows[2] = { NULL, NULL };
9483
90
    for (int axis = 0; axis < 2; axis++)
9484
60
        if (wheel[axis] != 0.0f)
9485
39
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9486
0
            {
9487
                // Bubble up into parent window if:
9488
                // - a child window doesn't allow any scrolling.
9489
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9490
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9491
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9492
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9493
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9494
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9495
0
                    break; // select this window
9496
0
            }
9497
30
    if (windows[0] == NULL && windows[1] == NULL)
9498
0
        return NULL;
9499
9500
    // If there's only one window or only one axis then there's no ambiguity
9501
30
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9502
30
        return windows[1] ? windows[1] : windows[0];
9503
9504
    // If candidate are different windows we need to decide which one to prioritize
9505
    // - First frame: only find a winner if one axis is zero.
9506
    // - Subsequent frames: only find a winner when one is more than the other.
9507
0
    if (g.WheelingWindowStartFrame == -1)
9508
0
        g.WheelingWindowStartFrame = g.FrameCount;
9509
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9510
0
    {
9511
0
        g.WheelingWindowWheelRemainder = wheel;
9512
0
        return NULL;
9513
0
    }
9514
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9515
0
}
9516
9517
// Called by NewFrame()
9518
void ImGui::UpdateMouseWheel()
9519
69.6k
{
9520
    // Reset the locked window if we move the mouse or after the timer elapses.
9521
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9522
69.6k
    ImGuiContext& g = *GImGui;
9523
69.6k
    if (g.WheelingWindow != NULL)
9524
10
    {
9525
10
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9526
10
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9527
0
            g.WheelingWindowReleaseTimer = 0.0f;
9528
10
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9529
10
            LockWheelingWindow(NULL, 0.0f);
9530
10
    }
9531
9532
69.6k
    ImVec2 wheel;
9533
69.6k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9534
69.6k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9535
9536
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9537
69.6k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9538
69.6k
    if (!mouse_window || mouse_window->Collapsed)
9539
67.2k
        return;
9540
9541
    // Zoom / Scale window
9542
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9543
2.44k
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9544
0
    {
9545
0
        LockWheelingWindow(mouse_window, wheel.y);
9546
0
        ImGuiWindow* window = mouse_window;
9547
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9548
0
        const float scale = new_font_scale / window->FontWindowScale;
9549
0
        window->FontWindowScale = new_font_scale;
9550
0
        if (window == window->RootWindow)
9551
0
        {
9552
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9553
0
            SetWindowPos(window, window->Pos + offset, 0);
9554
0
            window->Size = ImTrunc(window->Size * scale);
9555
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9556
0
        }
9557
0
        return;
9558
0
    }
9559
2.44k
    if (g.IO.KeyCtrl)
9560
0
        return;
9561
9562
    // Mouse wheel scrolling
9563
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9564
2.44k
    if (g.IO.MouseWheelRequestAxisSwap)
9565
0
        wheel = ImVec2(wheel.y, 0.0f);
9566
9567
    // Maintain a rough average of moving magnitude on both axises
9568
    // FIXME: should by based on wall clock time rather than frame-counter
9569
2.44k
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9570
2.44k
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9571
9572
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9573
2.44k
    wheel += g.WheelingWindowWheelRemainder;
9574
2.44k
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9575
2.44k
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9576
2.41k
        return;
9577
9578
    // Mouse wheel scrolling: find target and apply
9579
    // - don't renew lock if axis doesn't apply on the window.
9580
    // - select a main axis when both axises are being moved.
9581
30
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9582
30
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9583
30
        {
9584
30
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9585
30
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9586
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9587
30
            if (do_scroll[ImGuiAxis_X])
9588
8
            {
9589
8
                LockWheelingWindow(window, wheel.x);
9590
8
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9591
8
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9592
8
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9593
8
                g.WheelingWindowScrolledFrame = g.FrameCount;
9594
8
            }
9595
30
            if (do_scroll[ImGuiAxis_Y])
9596
2
            {
9597
2
                LockWheelingWindow(window, wheel.y);
9598
2
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9599
2
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9600
2
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9601
2
                g.WheelingWindowScrolledFrame = g.FrameCount;
9602
2
            }
9603
30
        }
9604
30
}
9605
9606
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9607
0
{
9608
0
    ImGuiContext& g = *GImGui;
9609
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9610
0
}
9611
9612
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9613
0
{
9614
0
    ImGuiContext& g = *GImGui;
9615
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9616
0
}
9617
9618
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9619
static const char* GetInputSourceName(ImGuiInputSource source)
9620
0
{
9621
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9622
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9623
0
    return input_source_names[source];
9624
0
}
9625
static const char* GetMouseSourceName(ImGuiMouseSource source)
9626
0
{
9627
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9628
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9629
0
    return mouse_source_names[source];
9630
0
}
9631
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9632
0
{
9633
0
    ImGuiContext& g = *GImGui;
9634
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9635
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9636
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9637
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9638
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9639
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9640
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9641
0
}
9642
#endif
9643
9644
// Process input queue
9645
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9646
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9647
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9648
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9649
69.6k
{
9650
69.6k
    ImGuiContext& g = *GImGui;
9651
69.6k
    ImGuiIO& io = g.IO;
9652
9653
    // Only trickle chars<>key when working with InputText()
9654
    // FIXME: InputText() could parse event trail?
9655
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9656
69.6k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9657
9658
69.6k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9659
69.6k
    int  mouse_button_changed = 0x00;
9660
69.6k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9661
9662
69.6k
    int event_n = 0;
9663
84.9k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9664
18.1k
    {
9665
18.1k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9666
18.1k
        if (e->Type == ImGuiInputEventType_MousePos)
9667
2.60k
        {
9668
2.60k
            if (g.IO.WantSetMousePos)
9669
0
                continue;
9670
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9671
2.60k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9672
2.60k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9673
171
                break;
9674
2.42k
            io.MousePos = event_pos;
9675
2.42k
            io.MouseSource = e->MousePos.MouseSource;
9676
2.42k
            mouse_moved = true;
9677
2.42k
        }
9678
15.5k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9679
4.51k
        {
9680
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9681
4.51k
            const ImGuiMouseButton button = e->MouseButton.Button;
9682
4.51k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9683
4.51k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9684
1.27k
                break;
9685
3.24k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9686
0
                break;
9687
3.24k
            io.MouseDown[button] = e->MouseButton.Down;
9688
3.24k
            io.MouseSource = e->MouseButton.MouseSource;
9689
3.24k
            mouse_button_changed |= (1 << button);
9690
3.24k
        }
9691
11.0k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9692
768
        {
9693
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9694
768
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9695
220
                break;
9696
548
            io.MouseWheelH += e->MouseWheel.WheelX;
9697
548
            io.MouseWheel += e->MouseWheel.WheelY;
9698
548
            io.MouseSource = e->MouseWheel.MouseSource;
9699
548
            mouse_wheeled = true;
9700
548
        }
9701
10.2k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9702
0
        {
9703
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9704
0
        }
9705
10.2k
        else if (e->Type == ImGuiInputEventType_Key)
9706
3.98k
        {
9707
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9708
3.98k
            ImGuiKey key = e->Key.Key;
9709
3.98k
            IM_ASSERT(key != ImGuiKey_None);
9710
3.98k
            ImGuiKeyData* key_data = GetKeyData(key);
9711
3.98k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9712
3.98k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9713
604
                break;
9714
3.37k
            key_data->Down = e->Key.Down;
9715
3.37k
            key_data->AnalogValue = e->Key.AnalogValue;
9716
3.37k
            key_changed = true;
9717
3.37k
            key_changed_mask.SetBit(key_data_index);
9718
9719
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9720
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9721
            io.KeysDown[key_data_index] = key_data->Down;
9722
            if (io.KeyMap[key_data_index] != -1)
9723
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9724
#endif
9725
3.37k
        }
9726
6.30k
        else if (e->Type == ImGuiInputEventType_Text)
9727
5.95k
        {
9728
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9729
5.95k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9730
678
                break;
9731
5.27k
            unsigned int c = e->Text.Char;
9732
5.27k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9733
5.27k
            if (trickle_interleaved_keys_and_text)
9734
0
                text_inputted = true;
9735
5.27k
        }
9736
348
        else if (e->Type == ImGuiInputEventType_Focus)
9737
348
        {
9738
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9739
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9740
348
            const bool focus_lost = !e->AppFocused.Focused;
9741
348
            io.AppFocusLost = focus_lost;
9742
348
        }
9743
0
        else
9744
0
        {
9745
0
            IM_ASSERT(0 && "Unknown event!");
9746
0
        }
9747
18.1k
    }
9748
9749
    // Record trail (for domain-specific applications wanting to access a precise trail)
9750
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9751
84.9k
    for (int n = 0; n < event_n; n++)
9752
15.2k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9753
9754
    // [DEBUG]
9755
69.6k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9756
69.6k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9757
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9758
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9759
69.6k
#endif
9760
9761
    // Remaining events will be processed on the next frame
9762
69.6k
    if (event_n == g.InputEventsQueue.Size)
9763
66.7k
        g.InputEventsQueue.resize(0);
9764
2.94k
    else
9765
2.94k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9766
9767
    // Clear buttons state when focus is lost
9768
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9769
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9770
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9771
69.6k
    if (g.IO.AppFocusLost)
9772
238
        g.IO.ClearInputKeys();
9773
69.6k
}
9774
9775
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9776
0
{
9777
0
    if (!IsNamedKeyOrModKey(key))
9778
0
        return ImGuiKeyOwner_None;
9779
9780
0
    ImGuiContext& g = *GImGui;
9781
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9782
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9783
9784
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9785
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9786
0
            return ImGuiKeyOwner_None;
9787
9788
0
    return owner_id;
9789
0
}
9790
9791
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9792
// TestKeyOwner(..., None) : (owner == None)
9793
// TestKeyOwner(..., Any)  : no owner test
9794
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9795
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9796
190k
{
9797
190k
    if (!IsNamedKeyOrModKey(key))
9798
0
        return true;
9799
9800
190k
    ImGuiContext& g = *GImGui;
9801
190k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9802
1.38k
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9803
8
            return false;
9804
9805
190k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9806
190k
    if (owner_id == ImGuiKeyOwner_Any)
9807
36.1k
        return (owner_data->LockThisFrame == false);
9808
9809
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9810
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9811
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9812
153k
    if (owner_data->OwnerCurr != owner_id)
9813
212
    {
9814
212
        if (owner_data->LockThisFrame)
9815
0
            return false;
9816
212
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9817
0
            return false;
9818
212
    }
9819
9820
153k
    return true;
9821
153k
}
9822
9823
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9824
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9825
// - SetKeyOwner(..., None)              : clears owner
9826
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9827
// - SetKeyOwner(..., Any or None, Lock) : set lock
9828
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9829
180
{
9830
180
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9831
180
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9832
9833
180
    ImGuiContext& g = *GImGui;
9834
180
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9835
180
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9836
9837
    // We cannot lock by default as it would likely break lots of legacy code.
9838
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9839
180
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9840
180
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9841
180
}
9842
9843
// Rarely used helper
9844
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9845
0
{
9846
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9847
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9848
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9849
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9850
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9851
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9852
0
}
9853
9854
// This is more or less equivalent to:
9855
//   if (IsItemHovered() || IsItemActive())
9856
//       SetKeyOwner(key, GetItemID());
9857
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9858
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9859
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9860
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9861
0
{
9862
0
    ImGuiContext& g = *GImGui;
9863
0
    ImGuiID id = g.LastItemData.ID;
9864
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9865
0
        return;
9866
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9867
0
        flags |= ImGuiInputFlags_CondDefault_;
9868
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9869
0
    {
9870
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9871
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9872
0
    }
9873
0
}
9874
9875
// This is the only public API until we expose owner_id versions of the API as replacements.
9876
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
9877
0
{
9878
0
    return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
9879
0
}
9880
9881
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
9882
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9883
139k
{
9884
139k
    ImGuiContext& g = *GImGui;
9885
139k
    if (key_chord & ImGuiMod_Shortcut)
9886
0
        key_chord = ConvertShortcutMod(key_chord);
9887
139k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9888
139k
    if (g.IO.KeyMods != mods)
9889
139k
        return false;
9890
9891
    // Special storage location for mods
9892
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9893
0
    if (key == ImGuiKey_None)
9894
0
        key = ConvertSingleModFlagToKey(&g, mods);
9895
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9896
0
        return false;
9897
0
    return true;
9898
0
}
9899
9900
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9901
139k
{
9902
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9903
139k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9904
139k
        flags |= ImGuiInputFlags_RouteFocused;
9905
139k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9906
0
        return false;
9907
9908
139k
    if (!IsKeyChordPressed(key_chord, owner_id, flags))
9909
139k
        return false;
9910
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9911
0
    return true;
9912
139k
}
9913
9914
9915
//-----------------------------------------------------------------------------
9916
// [SECTION] ERROR CHECKING
9917
//-----------------------------------------------------------------------------
9918
9919
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9920
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9921
// If this triggers you have an issue:
9922
// - Most commonly: mismatched headers and compiled code version.
9923
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9924
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9925
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9926
//   Otherwise it is possible that different compilation units would see different structure layout
9927
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9928
1
{
9929
1
    bool error = false;
9930
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9931
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9932
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9933
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9934
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9935
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9936
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9937
1
    return !error;
9938
1
}
9939
9940
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9941
// This is causing issues and ambiguity and we need to retire that.
9942
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9943
// [Scenario 1]
9944
//  Previously this would make the window content size ~200x200:
9945
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9946
//  Instead, please submit an item:
9947
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9948
//  Alternative:
9949
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9950
// [Scenario 2]
9951
//  For reference this is one of the issue what we aim to fix with this change:
9952
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9953
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9954
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9955
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9956
0
{
9957
0
    ImGuiContext& g = *GImGui;
9958
0
    ImGuiWindow* window = g.CurrentWindow;
9959
0
    IM_ASSERT(window->DC.IsSetPos);
9960
0
    window->DC.IsSetPos = false;
9961
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9962
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9963
0
        return;
9964
0
    if (window->SkipItems)
9965
0
        return;
9966
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9967
#else
9968
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9969
#endif
9970
0
}
9971
9972
static void ImGui::ErrorCheckNewFrameSanityChecks()
9973
69.6k
{
9974
69.6k
    ImGuiContext& g = *GImGui;
9975
9976
    // Check user IM_ASSERT macro
9977
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9978
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9979
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9980
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9981
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9982
69.6k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9983
9984
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9985
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9986
#ifdef __EMSCRIPTEN__
9987
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9988
        g.IO.DeltaTime = 0.00001f;
9989
#endif
9990
9991
    // Check user data
9992
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9993
69.6k
    IM_ASSERT(g.Initialized);
9994
69.6k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9995
69.6k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9996
69.6k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9997
69.6k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9998
69.6k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9999
69.6k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10000
69.6k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10001
69.6k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10002
69.6k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10003
69.6k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10004
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10005
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10006
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10007
10008
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10009
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10010
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10011
#endif
10012
10013
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10014
69.6k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10015
1
        g.IO.ConfigWindowsResizeFromEdges = false;
10016
10017
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10018
69.6k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10019
69.6k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10020
69.6k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10021
69.6k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10022
10023
    // Perform simple checks: multi-viewport and platform windows support
10024
69.6k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10025
1
    {
10026
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10027
0
        {
10028
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10029
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10030
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10031
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10032
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10033
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10034
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10035
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10036
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10037
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10038
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10039
0
        }
10040
1
        else
10041
1
        {
10042
            // Disable feature, our backends do not support it
10043
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10044
1
        }
10045
10046
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10047
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10048
0
        {
10049
0
            IM_UNUSED(mon);
10050
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10051
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10052
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10053
0
        }
10054
1
    }
10055
69.6k
}
10056
10057
static void ImGui::ErrorCheckEndFrameSanityChecks()
10058
69.6k
{
10059
69.6k
    ImGuiContext& g = *GImGui;
10060
10061
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10062
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10063
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10064
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10065
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10066
    // while still correctly asserting on mid-frame key press events.
10067
69.6k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10068
69.6k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10069
69.6k
    IM_UNUSED(key_mods);
10070
10071
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10072
    //ErrorCheckEndFrameRecover();
10073
10074
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10075
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10076
69.6k
    if (g.CurrentWindowStack.Size != 1)
10077
0
    {
10078
0
        if (g.CurrentWindowStack.Size > 1)
10079
0
        {
10080
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10081
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10082
0
            IM_UNUSED(window);
10083
0
            while (g.CurrentWindowStack.Size > 1)
10084
0
                End();
10085
0
        }
10086
0
        else
10087
0
        {
10088
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10089
0
        }
10090
0
    }
10091
10092
69.6k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10093
69.6k
}
10094
10095
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10096
// Must be called during or before EndFrame().
10097
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10098
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10099
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10100
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10101
0
{
10102
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10103
0
    ImGuiContext& g = *GImGui;
10104
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10105
0
    {
10106
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10107
0
        ImGuiWindow* window = g.CurrentWindow;
10108
0
        if (g.CurrentWindowStack.Size == 1)
10109
0
        {
10110
0
            IM_ASSERT(window->IsFallbackWindow);
10111
0
            break;
10112
0
        }
10113
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10114
0
        {
10115
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10116
0
            EndChild();
10117
0
        }
10118
0
        else
10119
0
        {
10120
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10121
0
            End();
10122
0
        }
10123
0
    }
10124
0
}
10125
10126
// Must be called before End()/EndChild()
10127
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10128
0
{
10129
0
    ImGuiContext& g = *GImGui;
10130
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10131
0
    {
10132
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10133
0
        EndTable();
10134
0
    }
10135
10136
0
    ImGuiWindow* window = g.CurrentWindow;
10137
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10138
0
    IM_ASSERT(window != NULL);
10139
0
    while (g.CurrentTabBar != NULL) //-V1044
10140
0
    {
10141
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10142
0
        EndTabBar();
10143
0
    }
10144
0
    while (window->DC.TreeDepth > 0)
10145
0
    {
10146
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10147
0
        TreePop();
10148
0
    }
10149
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10150
0
    {
10151
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10152
0
        EndGroup();
10153
0
    }
10154
0
    while (window->IDStack.Size > 1)
10155
0
    {
10156
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10157
0
        PopID();
10158
0
    }
10159
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10160
0
    {
10161
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10162
0
        EndDisabled();
10163
0
    }
10164
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10165
0
    {
10166
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10167
0
        PopStyleColor();
10168
0
    }
10169
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10170
0
    {
10171
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10172
0
        PopItemFlag();
10173
0
    }
10174
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10175
0
    {
10176
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10177
0
        PopStyleVar();
10178
0
    }
10179
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10180
0
    {
10181
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10182
0
        PopFont();
10183
0
    }
10184
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10185
0
    {
10186
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10187
0
        PopFocusScope();
10188
0
    }
10189
0
}
10190
10191
// Save current stack sizes for later compare
10192
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10193
188k
{
10194
188k
    ImGuiContext& g = *ctx;
10195
188k
    ImGuiWindow* window = g.CurrentWindow;
10196
188k
    SizeOfIDStack = (short)window->IDStack.Size;
10197
188k
    SizeOfColorStack = (short)g.ColorStack.Size;
10198
188k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10199
188k
    SizeOfFontStack = (short)g.FontStack.Size;
10200
188k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10201
188k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10202
188k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10203
188k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10204
188k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10205
188k
}
10206
10207
// Compare to detect usage errors
10208
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10209
188k
{
10210
188k
    ImGuiContext& g = *ctx;
10211
188k
    ImGuiWindow* window = g.CurrentWindow;
10212
188k
    IM_UNUSED(window);
10213
10214
    // Window stacks
10215
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10216
188k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10217
10218
    // Global stacks
10219
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10220
188k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10221
188k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10222
188k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10223
188k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10224
188k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10225
188k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10226
188k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10227
188k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10228
188k
}
10229
10230
10231
//-----------------------------------------------------------------------------
10232
// [SECTION] LAYOUT
10233
//-----------------------------------------------------------------------------
10234
// - ItemSize()
10235
// - ItemAdd()
10236
// - SameLine()
10237
// - GetCursorScreenPos()
10238
// - SetCursorScreenPos()
10239
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10240
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10241
// - GetCursorStartPos()
10242
// - Indent()
10243
// - Unindent()
10244
// - SetNextItemWidth()
10245
// - PushItemWidth()
10246
// - PushMultiItemsWidths()
10247
// - PopItemWidth()
10248
// - CalcItemWidth()
10249
// - CalcItemSize()
10250
// - GetTextLineHeight()
10251
// - GetTextLineHeightWithSpacing()
10252
// - GetFrameHeight()
10253
// - GetFrameHeightWithSpacing()
10254
// - GetContentRegionMax()
10255
// - GetContentRegionMaxAbs() [Internal]
10256
// - GetContentRegionAvail(),
10257
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10258
// - BeginGroup()
10259
// - EndGroup()
10260
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10261
//-----------------------------------------------------------------------------
10262
10263
// Advance cursor given item size for layout.
10264
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10265
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10266
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10267
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10268
72.2k
{
10269
72.2k
    ImGuiContext& g = *GImGui;
10270
72.2k
    ImGuiWindow* window = g.CurrentWindow;
10271
72.2k
    if (window->SkipItems)
10272
0
        return;
10273
10274
    // We increase the height in this function to accommodate for baseline offset.
10275
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10276
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10277
72.2k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10278
10279
72.2k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10280
72.2k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10281
10282
    // Always align ourselves on pixel boundaries
10283
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10284
72.2k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10285
72.2k
    window->DC.CursorPosPrevLine.y = line_y1;
10286
72.2k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10287
72.2k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10288
72.2k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10289
72.2k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10290
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10291
10292
72.2k
    window->DC.PrevLineSize.y = line_height;
10293
72.2k
    window->DC.CurrLineSize.y = 0.0f;
10294
72.2k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10295
72.2k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10296
72.2k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10297
10298
    // Horizontal layout mode
10299
72.2k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10300
0
        SameLine();
10301
72.2k
}
10302
10303
// Declare item bounding box for clipping and interaction.
10304
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10305
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10306
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10307
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10308
283k
{
10309
283k
    ImGuiContext& g = *GImGui;
10310
283k
    ImGuiWindow* window = g.CurrentWindow;
10311
10312
    // Set item data
10313
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10314
283k
    g.LastItemData.ID = id;
10315
283k
    g.LastItemData.Rect = bb;
10316
283k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10317
283k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10318
283k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10319
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10320
10321
283k
    if (id != 0)
10322
256k
    {
10323
256k
        KeepAliveID(id);
10324
10325
        // Directional navigation processing
10326
        // Runs prior to clipping early-out
10327
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10328
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10329
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10330
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10331
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10332
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10333
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10334
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10335
256k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10336
185k
        {
10337
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10338
185k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10339
185k
            if (g.NavId == id || g.NavAnyRequest)
10340
20.3k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10341
14.2k
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10342
14.2k
                        NavProcessItem();
10343
185k
        }
10344
256k
    }
10345
10346
    // Lightweight clear of SetNextItemXXX data.
10347
283k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10348
283k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10349
10350
#ifdef IMGUI_ENABLE_TEST_ENGINE
10351
    if (id != 0)
10352
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10353
#endif
10354
10355
    // Clipping test
10356
    // (this is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10357
    //const bool is_clipped = IsClippedEx(bb, id);
10358
    //if (is_clipped)
10359
    //    return false;
10360
283k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10361
283k
    if (!is_rect_visible)
10362
88.0k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10363
83.6k
            if (!g.LogEnabled)
10364
83.6k
                return false;
10365
10366
    // [DEBUG]
10367
199k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10368
199k
    if (id != 0)
10369
196k
    {
10370
196k
        if (id == g.DebugLocateId)
10371
0
            DebugLocateItemResolveWithLastItem();
10372
10373
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10374
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10375
        // READ THE FAQ: https://dearimgui.com/faq
10376
196k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10377
196k
    }
10378
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10379
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10380
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10381
199k
#endif
10382
10383
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10384
199k
    if (is_rect_visible)
10385
195k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10386
199k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10387
2.20k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10388
199k
    return true;
10389
283k
}
10390
10391
// Gets back to previous line and continue with horizontal layout
10392
//      offset_from_start_x == 0 : follow right after previous item
10393
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10394
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10395
//      spacing_w >= 0           : enforce spacing amount
10396
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10397
0
{
10398
0
    ImGuiContext& g = *GImGui;
10399
0
    ImGuiWindow* window = g.CurrentWindow;
10400
0
    if (window->SkipItems)
10401
0
        return;
10402
10403
0
    if (offset_from_start_x != 0.0f)
10404
0
    {
10405
0
        if (spacing_w < 0.0f)
10406
0
            spacing_w = 0.0f;
10407
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10408
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10409
0
    }
10410
0
    else
10411
0
    {
10412
0
        if (spacing_w < 0.0f)
10413
0
            spacing_w = g.Style.ItemSpacing.x;
10414
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10415
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10416
0
    }
10417
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10418
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10419
0
    window->DC.IsSameLine = true;
10420
0
}
10421
10422
ImVec2 ImGui::GetCursorScreenPos()
10423
57.3k
{
10424
57.3k
    ImGuiWindow* window = GetCurrentWindowRead();
10425
57.3k
    return window->DC.CursorPos;
10426
57.3k
}
10427
10428
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10429
0
{
10430
0
    ImGuiWindow* window = GetCurrentWindow();
10431
0
    window->DC.CursorPos = pos;
10432
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10433
0
    window->DC.IsSetPos = true;
10434
0
}
10435
10436
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10437
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10438
ImVec2 ImGui::GetCursorPos()
10439
0
{
10440
0
    ImGuiWindow* window = GetCurrentWindowRead();
10441
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10442
0
}
10443
10444
float ImGui::GetCursorPosX()
10445
0
{
10446
0
    ImGuiWindow* window = GetCurrentWindowRead();
10447
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10448
0
}
10449
10450
float ImGui::GetCursorPosY()
10451
0
{
10452
0
    ImGuiWindow* window = GetCurrentWindowRead();
10453
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10454
0
}
10455
10456
void ImGui::SetCursorPos(const ImVec2& local_pos)
10457
0
{
10458
0
    ImGuiWindow* window = GetCurrentWindow();
10459
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10460
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10461
0
    window->DC.IsSetPos = true;
10462
0
}
10463
10464
void ImGui::SetCursorPosX(float x)
10465
0
{
10466
0
    ImGuiWindow* window = GetCurrentWindow();
10467
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10468
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10469
0
    window->DC.IsSetPos = true;
10470
0
}
10471
10472
void ImGui::SetCursorPosY(float y)
10473
0
{
10474
0
    ImGuiWindow* window = GetCurrentWindow();
10475
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10476
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10477
0
    window->DC.IsSetPos = true;
10478
0
}
10479
10480
ImVec2 ImGui::GetCursorStartPos()
10481
0
{
10482
0
    ImGuiWindow* window = GetCurrentWindowRead();
10483
0
    return window->DC.CursorStartPos - window->Pos;
10484
0
}
10485
10486
void ImGui::Indent(float indent_w)
10487
0
{
10488
0
    ImGuiContext& g = *GImGui;
10489
0
    ImGuiWindow* window = GetCurrentWindow();
10490
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10491
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10492
0
}
10493
10494
void ImGui::Unindent(float indent_w)
10495
0
{
10496
0
    ImGuiContext& g = *GImGui;
10497
0
    ImGuiWindow* window = GetCurrentWindow();
10498
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10499
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10500
0
}
10501
10502
// Affect large frame+labels widgets only.
10503
void ImGui::SetNextItemWidth(float item_width)
10504
0
{
10505
0
    ImGuiContext& g = *GImGui;
10506
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10507
0
    g.NextItemData.Width = item_width;
10508
0
}
10509
10510
// FIXME: Remove the == 0.0f behavior?
10511
void ImGui::PushItemWidth(float item_width)
10512
0
{
10513
0
    ImGuiContext& g = *GImGui;
10514
0
    ImGuiWindow* window = g.CurrentWindow;
10515
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10516
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10517
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10518
0
}
10519
10520
void ImGui::PushMultiItemsWidths(int components, float w_full)
10521
0
{
10522
0
    ImGuiContext& g = *GImGui;
10523
0
    ImGuiWindow* window = g.CurrentWindow;
10524
0
    IM_ASSERT(components > 0);
10525
0
    const ImGuiStyle& style = g.Style;
10526
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10527
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10528
0
    float prev_split = w_items;
10529
0
    for (int i = components - 1; i > 0; i--)
10530
0
    {
10531
0
        float next_split = IM_TRUNC(w_items * i / components);
10532
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
10533
0
        prev_split = next_split;
10534
0
    }
10535
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
10536
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10537
0
}
10538
10539
void ImGui::PopItemWidth()
10540
0
{
10541
0
    ImGuiWindow* window = GetCurrentWindow();
10542
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10543
0
    window->DC.ItemWidthStack.pop_back();
10544
0
}
10545
10546
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10547
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10548
float ImGui::CalcItemWidth()
10549
0
{
10550
0
    ImGuiContext& g = *GImGui;
10551
0
    ImGuiWindow* window = g.CurrentWindow;
10552
0
    float w;
10553
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10554
0
        w = g.NextItemData.Width;
10555
0
    else
10556
0
        w = window->DC.ItemWidth;
10557
0
    if (w < 0.0f)
10558
0
    {
10559
0
        float region_max_x = GetContentRegionMaxAbs().x;
10560
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10561
0
    }
10562
0
    w = IM_TRUNC(w);
10563
0
    return w;
10564
0
}
10565
10566
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10567
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10568
// Note that only CalcItemWidth() is publicly exposed.
10569
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10570
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10571
49.0k
{
10572
49.0k
    ImGuiContext& g = *GImGui;
10573
49.0k
    ImGuiWindow* window = g.CurrentWindow;
10574
10575
49.0k
    ImVec2 region_max;
10576
49.0k
    if (size.x < 0.0f || size.y < 0.0f)
10577
0
        region_max = GetContentRegionMaxAbs();
10578
10579
49.0k
    if (size.x == 0.0f)
10580
5.44k
        size.x = default_w;
10581
43.6k
    else if (size.x < 0.0f)
10582
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10583
10584
49.0k
    if (size.y == 0.0f)
10585
3.32k
        size.y = default_h;
10586
45.7k
    else if (size.y < 0.0f)
10587
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10588
10589
49.0k
    return size;
10590
49.0k
}
10591
10592
float ImGui::GetTextLineHeight()
10593
0
{
10594
0
    ImGuiContext& g = *GImGui;
10595
0
    return g.FontSize;
10596
0
}
10597
10598
float ImGui::GetTextLineHeightWithSpacing()
10599
49.0k
{
10600
49.0k
    ImGuiContext& g = *GImGui;
10601
49.0k
    return g.FontSize + g.Style.ItemSpacing.y;
10602
49.0k
}
10603
10604
float ImGui::GetFrameHeight()
10605
865
{
10606
865
    ImGuiContext& g = *GImGui;
10607
865
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10608
865
}
10609
10610
float ImGui::GetFrameHeightWithSpacing()
10611
0
{
10612
0
    ImGuiContext& g = *GImGui;
10613
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10614
0
}
10615
10616
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10617
10618
// FIXME: This is in window space (not screen space!).
10619
ImVec2 ImGui::GetContentRegionMax()
10620
0
{
10621
0
    ImGuiContext& g = *GImGui;
10622
0
    ImGuiWindow* window = g.CurrentWindow;
10623
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10624
0
    return mx - window->Pos;
10625
0
}
10626
10627
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10628
ImVec2 ImGui::GetContentRegionMaxAbs()
10629
49.0k
{
10630
49.0k
    ImGuiContext& g = *GImGui;
10631
49.0k
    ImGuiWindow* window = g.CurrentWindow;
10632
49.0k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10633
49.0k
    return mx;
10634
49.0k
}
10635
10636
ImVec2 ImGui::GetContentRegionAvail()
10637
49.0k
{
10638
49.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
10639
49.0k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10640
49.0k
}
10641
10642
// In window space (not screen space!)
10643
ImVec2 ImGui::GetWindowContentRegionMin()
10644
0
{
10645
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10646
0
    return window->ContentRegionRect.Min - window->Pos;
10647
0
}
10648
10649
ImVec2 ImGui::GetWindowContentRegionMax()
10650
49.0k
{
10651
49.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
10652
49.0k
    return window->ContentRegionRect.Max - window->Pos;
10653
49.0k
}
10654
10655
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10656
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10657
// FIXME-OPT: Could we safely early out on ->SkipItems?
10658
void ImGui::BeginGroup()
10659
0
{
10660
0
    ImGuiContext& g = *GImGui;
10661
0
    ImGuiWindow* window = g.CurrentWindow;
10662
10663
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10664
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10665
0
    group_data.WindowID = window->ID;
10666
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10667
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10668
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10669
0
    group_data.BackupIndent = window->DC.Indent;
10670
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10671
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10672
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10673
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10674
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10675
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10676
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10677
0
    group_data.EmitItem = true;
10678
10679
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10680
0
    window->DC.Indent = window->DC.GroupOffset;
10681
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10682
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10683
0
    if (g.LogEnabled)
10684
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10685
0
}
10686
10687
void ImGui::EndGroup()
10688
0
{
10689
0
    ImGuiContext& g = *GImGui;
10690
0
    ImGuiWindow* window = g.CurrentWindow;
10691
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10692
10693
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10694
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10695
10696
0
    if (window->DC.IsSetPos)
10697
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10698
10699
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10700
10701
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10702
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10703
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10704
0
    window->DC.Indent = group_data.BackupIndent;
10705
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10706
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10707
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10708
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
10709
0
    if (g.LogEnabled)
10710
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10711
10712
0
    if (!group_data.EmitItem)
10713
0
    {
10714
0
        g.GroupStack.pop_back();
10715
0
        return;
10716
0
    }
10717
10718
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10719
0
    ItemSize(group_bb.GetSize());
10720
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10721
10722
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10723
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10724
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10725
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10726
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10727
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10728
0
    if (group_contains_curr_active_id)
10729
0
        g.LastItemData.ID = g.ActiveId;
10730
0
    else if (group_contains_prev_active_id)
10731
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10732
0
    g.LastItemData.Rect = group_bb;
10733
10734
    // Forward Hovered flag
10735
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10736
0
    if (group_contains_curr_hovered_id)
10737
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10738
10739
    // Forward Edited flag
10740
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10741
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10742
10743
    // Forward Deactivated flag
10744
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10745
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10746
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10747
10748
0
    g.GroupStack.pop_back();
10749
0
    if (g.DebugShowGroupRects)
10750
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10751
0
}
10752
10753
10754
//-----------------------------------------------------------------------------
10755
// [SECTION] SCROLLING
10756
//-----------------------------------------------------------------------------
10757
10758
// Helper to snap on edges when aiming at an item very close to the edge,
10759
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10760
// When we refactor the scrolling API this may be configurable with a flag?
10761
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10762
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10763
0
{
10764
0
    if (target <= snap_min + snap_threshold)
10765
0
        return ImLerp(snap_min, target, center_ratio);
10766
0
    if (target >= snap_max - snap_threshold)
10767
0
        return ImLerp(target, snap_max, center_ratio);
10768
0
    return target;
10769
0
}
10770
10771
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10772
189k
{
10773
189k
    ImVec2 scroll = window->Scroll;
10774
189k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10775
569k
    for (int axis = 0; axis < 2; axis++)
10776
379k
    {
10777
379k
        if (window->ScrollTarget[axis] < FLT_MAX)
10778
31.7k
        {
10779
31.7k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10780
31.7k
            float scroll_target = window->ScrollTarget[axis];
10781
31.7k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10782
0
            {
10783
0
                float snap_min = 0.0f;
10784
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10785
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10786
0
            }
10787
31.7k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10788
31.7k
        }
10789
379k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
10790
379k
        if (!window->Collapsed && !window->SkipItems)
10791
286k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10792
379k
    }
10793
189k
    return scroll;
10794
189k
}
10795
10796
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10797
0
{
10798
0
    ImGuiContext& g = *GImGui;
10799
0
    ImGuiWindow* window = g.CurrentWindow;
10800
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10801
0
}
10802
10803
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10804
0
{
10805
0
    ScrollToRectEx(window, item_rect, flags);
10806
0
}
10807
10808
// Scroll to keep newly navigated item fully into view
10809
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10810
1.39k
{
10811
1.39k
    ImGuiContext& g = *GImGui;
10812
1.39k
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10813
1.39k
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10814
1.39k
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10815
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10816
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10817
10818
    // Check that only one behavior is selected per axis
10819
1.39k
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10820
1.39k
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10821
10822
    // Defaults
10823
1.39k
    ImGuiScrollFlags in_flags = flags;
10824
1.39k
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10825
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10826
1.39k
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10827
1.33k
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10828
10829
1.39k
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10830
1.39k
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10831
1.39k
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10832
1.39k
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10833
10834
1.39k
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10835
5
    {
10836
5
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10837
5
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10838
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10839
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10840
5
    }
10841
1.38k
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10842
0
    {
10843
0
        if (can_be_fully_visible_x)
10844
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10845
0
        else
10846
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10847
0
    }
10848
10849
1.39k
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10850
3
    {
10851
3
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10852
3
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10853
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10854
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10855
3
    }
10856
1.38k
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10857
0
    {
10858
0
        if (can_be_fully_visible_y)
10859
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10860
0
        else
10861
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10862
0
    }
10863
10864
1.39k
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10865
1.39k
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10866
10867
    // Also scroll parent window to keep us into view if necessary
10868
1.39k
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10869
0
    {
10870
        // FIXME-SCROLL: May be an option?
10871
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10872
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10873
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10874
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10875
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10876
0
    }
10877
10878
1.39k
    return delta_scroll;
10879
1.39k
}
10880
10881
float ImGui::GetScrollX()
10882
65.3k
{
10883
65.3k
    ImGuiWindow* window = GImGui->CurrentWindow;
10884
65.3k
    return window->Scroll.x;
10885
65.3k
}
10886
10887
float ImGui::GetScrollY()
10888
65.3k
{
10889
65.3k
    ImGuiWindow* window = GImGui->CurrentWindow;
10890
65.3k
    return window->Scroll.y;
10891
65.3k
}
10892
10893
float ImGui::GetScrollMaxX()
10894
0
{
10895
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10896
0
    return window->ScrollMax.x;
10897
0
}
10898
10899
float ImGui::GetScrollMaxY()
10900
0
{
10901
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10902
0
    return window->ScrollMax.y;
10903
0
}
10904
10905
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10906
16.4k
{
10907
16.4k
    window->ScrollTarget.x = scroll_x;
10908
16.4k
    window->ScrollTargetCenterRatio.x = 0.0f;
10909
16.4k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10910
16.4k
}
10911
10912
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10913
16.1k
{
10914
16.1k
    window->ScrollTarget.y = scroll_y;
10915
16.1k
    window->ScrollTargetCenterRatio.y = 0.0f;
10916
16.1k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10917
16.1k
}
10918
10919
void ImGui::SetScrollX(float scroll_x)
10920
15.8k
{
10921
15.8k
    ImGuiContext& g = *GImGui;
10922
15.8k
    SetScrollX(g.CurrentWindow, scroll_x);
10923
15.8k
}
10924
10925
void ImGui::SetScrollY(float scroll_y)
10926
14.6k
{
10927
14.6k
    ImGuiContext& g = *GImGui;
10928
14.6k
    SetScrollY(g.CurrentWindow, scroll_y);
10929
14.6k
}
10930
10931
// Note that a local position will vary depending on initial scroll value,
10932
// This is a little bit confusing so bear with us:
10933
//  - local_pos = (absolution_pos - window->Pos)
10934
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10935
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10936
//  - They mostly exist because of legacy API.
10937
// Following the rules above, when trying to work with scrolling code, consider that:
10938
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10939
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10940
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10941
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10942
5
{
10943
5
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10944
5
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10945
5
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10946
5
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10947
5
}
10948
10949
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10950
3
{
10951
3
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10952
3
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10953
3
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10954
3
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10955
3
}
10956
10957
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10958
0
{
10959
0
    ImGuiContext& g = *GImGui;
10960
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10961
0
}
10962
10963
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10964
0
{
10965
0
    ImGuiContext& g = *GImGui;
10966
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10967
0
}
10968
10969
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10970
void ImGui::SetScrollHereX(float center_x_ratio)
10971
0
{
10972
0
    ImGuiContext& g = *GImGui;
10973
0
    ImGuiWindow* window = g.CurrentWindow;
10974
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10975
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10976
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10977
10978
    // Tweak: snap on edges when aiming at an item very close to the edge
10979
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10980
0
}
10981
10982
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10983
void ImGui::SetScrollHereY(float center_y_ratio)
10984
0
{
10985
0
    ImGuiContext& g = *GImGui;
10986
0
    ImGuiWindow* window = g.CurrentWindow;
10987
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10988
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10989
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10990
10991
    // Tweak: snap on edges when aiming at an item very close to the edge
10992
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10993
0
}
10994
10995
//-----------------------------------------------------------------------------
10996
// [SECTION] TOOLTIPS
10997
//-----------------------------------------------------------------------------
10998
10999
bool ImGui::BeginTooltip()
11000
0
{
11001
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11002
0
}
11003
11004
bool ImGui::BeginItemTooltip()
11005
0
{
11006
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11007
0
        return false;
11008
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11009
0
}
11010
11011
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11012
0
{
11013
0
    ImGuiContext& g = *GImGui;
11014
11015
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11016
0
    {
11017
        // Drag and Drop tooltips are positioning differently than other tooltips:
11018
        // - offset visibility to increase visibility around mouse.
11019
        // - never clamp within outer viewport boundary.
11020
        // We call SetNextWindowPos() to enforce position and disable clamping.
11021
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11022
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11023
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11024
0
        SetNextWindowPos(tooltip_pos);
11025
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11026
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11027
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11028
0
    }
11029
11030
0
    char window_name[16];
11031
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11032
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11033
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11034
0
            if (window->Active)
11035
0
            {
11036
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11037
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11038
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11039
0
            }
11040
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11041
0
    Begin(window_name, NULL, flags | extra_window_flags);
11042
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11043
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11044
    //if (!ret)
11045
    //    End();
11046
    //return ret;
11047
0
    return true;
11048
0
}
11049
11050
void ImGui::EndTooltip()
11051
0
{
11052
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11053
0
    End();
11054
0
}
11055
11056
void ImGui::SetTooltip(const char* fmt, ...)
11057
0
{
11058
0
    va_list args;
11059
0
    va_start(args, fmt);
11060
0
    SetTooltipV(fmt, args);
11061
0
    va_end(args);
11062
0
}
11063
11064
void ImGui::SetTooltipV(const char* fmt, va_list args)
11065
0
{
11066
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11067
0
        return;
11068
0
    TextV(fmt, args);
11069
0
    EndTooltip();
11070
0
}
11071
11072
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11073
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11074
void ImGui::SetItemTooltip(const char* fmt, ...)
11075
0
{
11076
0
    va_list args;
11077
0
    va_start(args, fmt);
11078
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11079
0
        SetTooltipV(fmt, args);
11080
0
    va_end(args);
11081
0
}
11082
11083
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11084
0
{
11085
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11086
0
        SetTooltipV(fmt, args);
11087
0
}
11088
11089
11090
//-----------------------------------------------------------------------------
11091
// [SECTION] POPUPS
11092
//-----------------------------------------------------------------------------
11093
11094
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11095
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11096
0
{
11097
0
    ImGuiContext& g = *GImGui;
11098
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11099
0
    {
11100
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11101
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11102
0
        IM_ASSERT(id == 0);
11103
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11104
0
            return g.OpenPopupStack.Size > 0;
11105
0
        else
11106
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11107
0
    }
11108
0
    else
11109
0
    {
11110
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11111
0
        {
11112
            // Return true if the popup is open anywhere in the popup stack
11113
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11114
0
                if (popup_data.PopupId == id)
11115
0
                    return true;
11116
0
            return false;
11117
0
        }
11118
0
        else
11119
0
        {
11120
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11121
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11122
0
        }
11123
0
    }
11124
0
}
11125
11126
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11127
0
{
11128
0
    ImGuiContext& g = *GImGui;
11129
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11130
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11131
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11132
0
    return IsPopupOpen(id, popup_flags);
11133
0
}
11134
11135
// Also see FindBlockingModal(NULL)
11136
ImGuiWindow* ImGui::GetTopMostPopupModal()
11137
209k
{
11138
209k
    ImGuiContext& g = *GImGui;
11139
209k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11140
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11141
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11142
0
                return popup;
11143
209k
    return NULL;
11144
209k
}
11145
11146
// See Demo->Stacked Modal to confirm what this is for.
11147
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11148
69.6k
{
11149
69.6k
    ImGuiContext& g = *GImGui;
11150
69.6k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11151
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11152
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11153
0
                return popup;
11154
69.6k
    return NULL;
11155
69.6k
}
11156
11157
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11158
0
{
11159
0
    ImGuiContext& g = *GImGui;
11160
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11161
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11162
0
    OpenPopupEx(id, popup_flags);
11163
0
}
11164
11165
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11166
0
{
11167
0
    OpenPopupEx(id, popup_flags);
11168
0
}
11169
11170
// Mark popup as open (toggle toward open state).
11171
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11172
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11173
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11174
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11175
0
{
11176
0
    ImGuiContext& g = *GImGui;
11177
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11178
0
    const int current_stack_size = g.BeginPopupStack.Size;
11179
11180
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11181
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11182
0
            return;
11183
11184
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11185
0
    popup_ref.PopupId = id;
11186
0
    popup_ref.Window = NULL;
11187
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
11188
0
    popup_ref.OpenFrameCount = g.FrameCount;
11189
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11190
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11191
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11192
11193
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11194
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11195
0
    {
11196
0
        g.OpenPopupStack.push_back(popup_ref);
11197
0
    }
11198
0
    else
11199
0
    {
11200
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
11201
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
11202
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
11203
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
11204
0
        {
11205
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11206
0
        }
11207
0
        else
11208
0
        {
11209
            // Close child popups if any, then flag popup for open/reopen
11210
0
            ClosePopupToLevel(current_stack_size, false);
11211
0
            g.OpenPopupStack.push_back(popup_ref);
11212
0
        }
11213
11214
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11215
        // This is equivalent to what ClosePopupToLevel() does.
11216
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11217
        //    FocusWindow(parent_window);
11218
0
    }
11219
0
}
11220
11221
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11222
// This function closes any popups that are over 'ref_window'.
11223
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11224
11.2k
{
11225
11.2k
    ImGuiContext& g = *GImGui;
11226
11.2k
    if (g.OpenPopupStack.Size == 0)
11227
11.2k
        return;
11228
11229
    // Don't close our own child popup windows.
11230
0
    int popup_count_to_keep = 0;
11231
0
    if (ref_window)
11232
0
    {
11233
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11234
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11235
0
        {
11236
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11237
0
            if (!popup.Window)
11238
0
                continue;
11239
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11240
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
11241
0
                continue;
11242
11243
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11244
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
11245
            //     Window -> Popup1 -> Popup2 -> Popup3
11246
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11247
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11248
0
            bool ref_window_is_descendent_of_popup = false;
11249
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11250
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11251
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11252
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11253
0
                    {
11254
0
                        ref_window_is_descendent_of_popup = true;
11255
0
                        break;
11256
0
                    }
11257
0
            if (!ref_window_is_descendent_of_popup)
11258
0
                break;
11259
0
        }
11260
0
    }
11261
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11262
0
    {
11263
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11264
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11265
0
    }
11266
0
}
11267
11268
void ImGui::ClosePopupsExceptModals()
11269
0
{
11270
0
    ImGuiContext& g = *GImGui;
11271
11272
0
    int popup_count_to_keep;
11273
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11274
0
    {
11275
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11276
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11277
0
            break;
11278
0
    }
11279
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11280
0
        ClosePopupToLevel(popup_count_to_keep, true);
11281
0
}
11282
11283
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11284
0
{
11285
0
    ImGuiContext& g = *GImGui;
11286
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
11287
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11288
11289
    // Trim open popup stack
11290
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
11291
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
11292
0
    g.OpenPopupStack.resize(remaining);
11293
11294
0
    if (restore_focus_to_window_under_popup)
11295
0
    {
11296
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
11297
0
        if (focus_window && !focus_window->WasActive && popup_window)
11298
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11299
0
        else
11300
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11301
0
    }
11302
0
}
11303
11304
// Close the popup we have begin-ed into.
11305
void ImGui::CloseCurrentPopup()
11306
0
{
11307
0
    ImGuiContext& g = *GImGui;
11308
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11309
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11310
0
        return;
11311
11312
    // Closing a menu closes its top-most parent popup (unless a modal)
11313
0
    while (popup_idx > 0)
11314
0
    {
11315
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11316
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11317
0
        bool close_parent = false;
11318
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11319
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11320
0
                close_parent = true;
11321
0
        if (!close_parent)
11322
0
            break;
11323
0
        popup_idx--;
11324
0
    }
11325
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11326
0
    ClosePopupToLevel(popup_idx, true);
11327
11328
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11329
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11330
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11331
0
    if (ImGuiWindow* window = g.NavWindow)
11332
0
        window->DC.NavHideHighlightOneFrame = true;
11333
0
}
11334
11335
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11336
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11337
0
{
11338
0
    ImGuiContext& g = *GImGui;
11339
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11340
0
    {
11341
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11342
0
        return false;
11343
0
    }
11344
11345
0
    char name[20];
11346
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11347
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11348
0
    else
11349
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11350
11351
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11352
0
    bool is_open = Begin(name, NULL, flags);
11353
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11354
0
        EndPopup();
11355
11356
0
    return is_open;
11357
0
}
11358
11359
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11360
0
{
11361
0
    ImGuiContext& g = *GImGui;
11362
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11363
0
    {
11364
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11365
0
        return false;
11366
0
    }
11367
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11368
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11369
0
    return BeginPopupEx(id, flags);
11370
0
}
11371
11372
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11373
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11374
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11375
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11376
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11377
0
{
11378
0
    ImGuiContext& g = *GImGui;
11379
0
    ImGuiWindow* window = g.CurrentWindow;
11380
0
    const ImGuiID id = window->GetID(name);
11381
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11382
0
    {
11383
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11384
0
        if (p_open && *p_open)
11385
0
            *p_open = false;
11386
0
        return false;
11387
0
    }
11388
11389
    // Center modal windows by default for increased visibility
11390
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11391
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11392
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11393
0
    {
11394
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11395
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11396
0
    }
11397
11398
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11399
0
    const bool is_open = Begin(name, p_open, flags);
11400
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11401
0
    {
11402
0
        EndPopup();
11403
0
        if (is_open)
11404
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11405
0
        return false;
11406
0
    }
11407
0
    return is_open;
11408
0
}
11409
11410
void ImGui::EndPopup()
11411
0
{
11412
0
    ImGuiContext& g = *GImGui;
11413
0
    ImGuiWindow* window = g.CurrentWindow;
11414
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11415
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11416
11417
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11418
0
    if (g.NavWindow == window)
11419
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11420
11421
    // Child-popups don't need to be laid out
11422
0
    IM_ASSERT(g.WithinEndChild == false);
11423
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11424
0
        g.WithinEndChild = true;
11425
0
    End();
11426
0
    g.WithinEndChild = false;
11427
0
}
11428
11429
// Helper to open a popup if mouse button is released over the item
11430
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11431
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11432
0
{
11433
0
    ImGuiContext& g = *GImGui;
11434
0
    ImGuiWindow* window = g.CurrentWindow;
11435
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11436
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11437
0
    {
11438
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11439
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11440
0
        OpenPopupEx(id, popup_flags);
11441
0
    }
11442
0
}
11443
11444
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11445
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11446
// - To create a popup with a specific identifier, pass it in str_id.
11447
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11448
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11449
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11450
//   This is essentially the same as:
11451
//       id = str_id ? GetID(str_id) : GetItemID();
11452
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11453
//       return BeginPopup(id);
11454
//   Which is essentially the same as:
11455
//       id = str_id ? GetID(str_id) : GetItemID();
11456
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11457
//           OpenPopup(id);
11458
//       return BeginPopup(id);
11459
//   The main difference being that this is tweaked to avoid computing the ID twice.
11460
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11461
0
{
11462
0
    ImGuiContext& g = *GImGui;
11463
0
    ImGuiWindow* window = g.CurrentWindow;
11464
0
    if (window->SkipItems)
11465
0
        return false;
11466
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11467
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11468
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11469
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11470
0
        OpenPopupEx(id, popup_flags);
11471
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11472
0
}
11473
11474
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11475
0
{
11476
0
    ImGuiContext& g = *GImGui;
11477
0
    ImGuiWindow* window = g.CurrentWindow;
11478
0
    if (!str_id)
11479
0
        str_id = "window_context";
11480
0
    ImGuiID id = window->GetID(str_id);
11481
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11482
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11483
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11484
0
            OpenPopupEx(id, popup_flags);
11485
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11486
0
}
11487
11488
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11489
0
{
11490
0
    ImGuiContext& g = *GImGui;
11491
0
    ImGuiWindow* window = g.CurrentWindow;
11492
0
    if (!str_id)
11493
0
        str_id = "void_context";
11494
0
    ImGuiID id = window->GetID(str_id);
11495
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11496
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11497
0
        if (GetTopMostPopupModal() == NULL)
11498
0
            OpenPopupEx(id, popup_flags);
11499
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11500
0
}
11501
11502
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11503
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11504
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11505
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11506
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11507
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11508
0
{
11509
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11510
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11511
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11512
11513
    // Combo Box policy (we want a connecting edge)
11514
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11515
0
    {
11516
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11517
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11518
0
        {
11519
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11520
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11521
0
                continue;
11522
0
            ImVec2 pos;
11523
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11524
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11525
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11526
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11527
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11528
0
                continue;
11529
0
            *last_dir = dir;
11530
0
            return pos;
11531
0
        }
11532
0
    }
11533
11534
    // Tooltip and Default popup policy
11535
    // (Always first try the direction we used on the last frame, if any)
11536
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11537
0
    {
11538
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11539
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11540
0
        {
11541
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11542
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11543
0
                continue;
11544
11545
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11546
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11547
11548
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11549
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11550
0
                continue;
11551
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11552
0
                continue;
11553
11554
0
            ImVec2 pos;
11555
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11556
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11557
11558
            // Clamp top-left corner of popup
11559
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11560
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11561
11562
0
            *last_dir = dir;
11563
0
            return pos;
11564
0
        }
11565
0
    }
11566
11567
    // Fallback when not enough room:
11568
0
    *last_dir = ImGuiDir_None;
11569
11570
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11571
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11572
0
        return ref_pos + ImVec2(2, 2);
11573
11574
    // Otherwise try to keep within display
11575
0
    ImVec2 pos = ref_pos;
11576
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11577
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11578
0
    return pos;
11579
0
}
11580
11581
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11582
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11583
0
{
11584
0
    ImGuiContext& g = *GImGui;
11585
0
    ImRect r_screen;
11586
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11587
0
    {
11588
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11589
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11590
0
        r_screen.Min = monitor.WorkPos;
11591
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11592
0
    }
11593
0
    else
11594
0
    {
11595
        // Use the full viewport area (not work area) for popups
11596
0
        r_screen = window->Viewport->GetMainRect();
11597
0
    }
11598
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11599
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11600
0
    return r_screen;
11601
0
}
11602
11603
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11604
0
{
11605
0
    ImGuiContext& g = *GImGui;
11606
11607
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11608
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11609
0
    {
11610
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11611
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11612
0
        ImGuiWindow* parent_window = window->ParentWindow;
11613
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11614
0
        ImRect r_avoid;
11615
0
        if (parent_window->DC.MenuBarAppending)
11616
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11617
0
        else
11618
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11619
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11620
0
    }
11621
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11622
0
    {
11623
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11624
0
    }
11625
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11626
0
    {
11627
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11628
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11629
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11630
0
        IM_ASSERT(g.CurrentWindow == window);
11631
0
        const float scale = g.Style.MouseCursorScale;
11632
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11633
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11634
0
        ImRect r_avoid;
11635
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11636
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11637
0
        else
11638
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11639
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11640
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11641
0
    }
11642
0
    IM_ASSERT(0);
11643
0
    return window->Pos;
11644
0
}
11645
11646
//-----------------------------------------------------------------------------
11647
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11648
//-----------------------------------------------------------------------------
11649
11650
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11651
// In our terminology those should be interchangeable, yet right now this is super confusing.
11652
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11653
11654
void ImGui::SetNavWindow(ImGuiWindow* window)
11655
11.2k
{
11656
11.2k
    ImGuiContext& g = *GImGui;
11657
11.2k
    if (g.NavWindow != window)
11658
11.2k
    {
11659
11.2k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11660
11.2k
        g.NavWindow = window;
11661
11.2k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11662
11.2k
    }
11663
11.2k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11664
11.2k
    NavUpdateAnyRequestFlag();
11665
11.2k
}
11666
11667
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11668
5.99k
{
11669
5.99k
    ImGuiContext& g = *GImGui;
11670
5.99k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11671
5.99k
}
11672
11673
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11674
1.98k
{
11675
1.98k
    ImGuiContext& g = *GImGui;
11676
1.98k
    IM_ASSERT(g.NavWindow != NULL);
11677
1.98k
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11678
1.98k
    g.NavId = id;
11679
1.98k
    g.NavLayer = nav_layer;
11680
1.98k
    g.NavFocusScopeId = focus_scope_id;
11681
1.98k
    g.NavWindow->NavLastIds[nav_layer] = id;
11682
1.98k
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11683
11684
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11685
1.98k
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11686
1.98k
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11687
1.98k
}
11688
11689
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11690
169
{
11691
169
    ImGuiContext& g = *GImGui;
11692
169
    IM_ASSERT(id != 0);
11693
11694
169
    if (g.NavWindow != window)
11695
96
       SetNavWindow(window);
11696
11697
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11698
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11699
169
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11700
169
    g.NavId = id;
11701
169
    g.NavLayer = nav_layer;
11702
169
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11703
169
    window->NavLastIds[nav_layer] = id;
11704
169
    if (g.LastItemData.ID == id)
11705
169
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11706
11707
169
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11708
0
        g.NavDisableMouseHover = true;
11709
169
    else
11710
169
        g.NavDisableHighlight = true;
11711
11712
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11713
169
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11714
169
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11715
169
}
11716
11717
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11718
2.44k
{
11719
2.44k
    if (ImFabs(dx) > ImFabs(dy))
11720
161
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11721
2.28k
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11722
2.44k
}
11723
11724
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11725
4.97k
{
11726
4.97k
    if (cand_max < curr_min)
11727
2.24k
        return cand_max - curr_min;
11728
2.72k
    if (curr_max < cand_min)
11729
37
        return cand_min - curr_max;
11730
2.69k
    return 0.0f;
11731
2.72k
}
11732
11733
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11734
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11735
5.61k
{
11736
5.61k
    ImGuiContext& g = *GImGui;
11737
5.61k
    ImGuiWindow* window = g.CurrentWindow;
11738
5.61k
    if (g.NavLayer != window->DC.NavLayerCurrent)
11739
3.13k
        return false;
11740
11741
    // FIXME: Those are not good variables names
11742
2.48k
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11743
2.48k
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11744
2.48k
    g.NavScoringDebugCount++;
11745
11746
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11747
2.48k
    if (window->ParentWindow == g.NavWindow)
11748
0
    {
11749
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11750
0
        if (!window->ClipRect.Overlaps(cand))
11751
0
            return false;
11752
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11753
0
    }
11754
11755
    // Compute distance between boxes
11756
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11757
2.48k
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11758
2.48k
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11759
2.48k
    if (dby != 0.0f && dbx != 0.0f)
11760
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11761
2.48k
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11762
11763
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11764
2.48k
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11765
2.48k
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11766
2.48k
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11767
11768
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11769
2.48k
    ImGuiDir quadrant;
11770
2.48k
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11771
2.48k
    if (dbx != 0.0f || dby != 0.0f)
11772
2.27k
    {
11773
        // For non-overlapping boxes, use distance between boxes
11774
2.27k
        dax = dbx;
11775
2.27k
        day = dby;
11776
2.27k
        dist_axial = dist_box;
11777
2.27k
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11778
2.27k
    }
11779
206
    else if (dcx != 0.0f || dcy != 0.0f)
11780
165
    {
11781
        // For overlapping boxes with different centers, use distance between centers
11782
165
        dax = dcx;
11783
165
        day = dcy;
11784
165
        dist_axial = dist_center;
11785
165
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11786
165
    }
11787
41
    else
11788
41
    {
11789
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11790
41
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11791
41
    }
11792
11793
2.48k
    const ImGuiDir move_dir = g.NavMoveDir;
11794
#if IMGUI_DEBUG_NAV_SCORING
11795
    char buf[200];
11796
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11797
    {
11798
        if (quadrant == move_dir)
11799
        {
11800
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11801
            ImDrawList* draw_list = GetForegroundDrawList(window);
11802
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11803
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11804
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11805
        }
11806
    }
11807
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11808
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11809
    if (debug_hovering || debug_tty)
11810
    {
11811
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11812
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11813
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11814
        if (debug_hovering)
11815
        {
11816
            ImDrawList* draw_list = GetForegroundDrawList(window);
11817
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11818
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11819
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11820
            draw_list->AddText(cand.Max, ~0U, buf);
11821
        }
11822
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11823
    }
11824
#endif
11825
11826
    // Is it in the quadrant we're interested in moving to?
11827
2.48k
    bool new_best = false;
11828
2.48k
    if (quadrant == move_dir)
11829
2.32k
    {
11830
        // Does it beat the current best candidate?
11831
2.32k
        if (dist_box < result->DistBox)
11832
2.32k
        {
11833
2.32k
            result->DistBox = dist_box;
11834
2.32k
            result->DistCenter = dist_center;
11835
2.32k
            return true;
11836
2.32k
        }
11837
0
        if (dist_box == result->DistBox)
11838
0
        {
11839
            // Try using distance between center points to break ties
11840
0
            if (dist_center < result->DistCenter)
11841
0
            {
11842
0
                result->DistCenter = dist_center;
11843
0
                new_best = true;
11844
0
            }
11845
0
            else if (dist_center == result->DistCenter)
11846
0
            {
11847
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11848
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11849
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11850
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11851
0
                    new_best = true;
11852
0
            }
11853
0
        }
11854
0
    }
11855
11856
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11857
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11858
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11859
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11860
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11861
159
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11862
159
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11863
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11864
0
            {
11865
0
                result->DistAxial = dist_axial;
11866
0
                new_best = true;
11867
0
            }
11868
11869
159
    return new_best;
11870
2.48k
}
11871
11872
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11873
2.43k
{
11874
2.43k
    ImGuiContext& g = *GImGui;
11875
2.43k
    ImGuiWindow* window = g.CurrentWindow;
11876
2.43k
    result->Window = window;
11877
2.43k
    result->ID = g.LastItemData.ID;
11878
2.43k
    result->FocusScopeId = g.CurrentFocusScopeId;
11879
2.43k
    result->InFlags = g.LastItemData.InFlags;
11880
2.43k
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11881
2.43k
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
11882
0
    {
11883
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11884
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11885
0
    }
11886
2.43k
}
11887
11888
// True when current work location may be scrolled horizontally when moving left / right.
11889
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11890
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11891
307k
{
11892
307k
    ImGuiContext& g = *GImGui;
11893
307k
    ImGuiWindow* window = g.CurrentWindow;
11894
307k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11895
307k
}
11896
11897
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11898
// This is called after LastItemData is set, but NextItemData is also still valid.
11899
static void ImGui::NavProcessItem()
11900
14.2k
{
11901
14.2k
    ImGuiContext& g = *GImGui;
11902
14.2k
    ImGuiWindow* window = g.CurrentWindow;
11903
14.2k
    const ImGuiID id = g.LastItemData.ID;
11904
14.2k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11905
11906
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11907
14.2k
    if (window->DC.NavIsScrollPushableX == false)
11908
0
    {
11909
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11910
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11911
0
    }
11912
14.2k
    const ImRect nav_bb = g.LastItemData.NavRect;
11913
11914
    // Process Init Request
11915
14.2k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11916
49
    {
11917
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11918
49
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11919
49
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11920
49
        {
11921
49
            NavApplyItemToResult(&g.NavInitResult);
11922
49
        }
11923
49
        if (candidate_for_nav_default_focus)
11924
49
        {
11925
49
            g.NavInitRequest = false; // Found a match, clear request
11926
49
            NavUpdateAnyRequestFlag();
11927
49
        }
11928
49
    }
11929
11930
    // Process Move Request (scoring for navigation)
11931
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11932
14.2k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11933
3.77k
    {
11934
3.77k
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
11935
3.77k
        if (is_tabbing)
11936
132
        {
11937
132
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11938
132
        }
11939
3.64k
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11940
3.37k
        {
11941
3.37k
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11942
3.37k
            if (NavScoreItem(result))
11943
1.38k
                NavApplyItemToResult(result);
11944
11945
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11946
3.37k
            const float VISIBLE_RATIO = 0.70f;
11947
3.37k
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11948
2.49k
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11949
2.23k
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11950
943
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11951
3.37k
        }
11952
3.77k
    }
11953
11954
    // Update information for currently focused/navigated item
11955
14.2k
    if (g.NavId == id)
11956
12.2k
    {
11957
12.2k
        if (g.NavWindow != window)
11958
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11959
12.2k
        g.NavLayer = window->DC.NavLayerCurrent;
11960
12.2k
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11961
12.2k
        g.NavIdIsAlive = true;
11962
12.2k
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
11963
0
        {
11964
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11965
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11966
0
        }
11967
12.2k
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11968
12.2k
    }
11969
14.2k
}
11970
11971
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11972
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11973
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11974
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11975
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11976
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11977
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11978
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11979
132
{
11980
132
    ImGuiContext& g = *GImGui;
11981
11982
132
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11983
132
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11984
67
            return;
11985
65
    if (g.NavFocusScopeId != g.CurrentFocusScopeId)
11986
5
        return;
11987
11988
    // - Can always land on an item when using API call.
11989
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11990
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11991
60
    bool can_stop;
11992
60
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11993
0
        can_stop = true;
11994
60
    else
11995
60
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11996
11997
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11998
60
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11999
60
    if (g.NavTabbingDir == +1)
12000
60
    {
12001
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12002
60
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12003
60
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12004
60
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12005
0
            NavMoveRequestResolveWithLastItem(result);
12006
60
        else if (g.NavId == id)
12007
58
            g.NavTabbingCounter = 1;
12008
60
    }
12009
0
    else if (g.NavTabbingDir == -1)
12010
0
    {
12011
        // Tab Backward
12012
0
        if (g.NavId == id)
12013
0
        {
12014
0
            if (result->ID)
12015
0
            {
12016
0
                g.NavMoveScoringItems = false;
12017
0
                NavUpdateAnyRequestFlag();
12018
0
            }
12019
0
        }
12020
0
        else if (can_stop)
12021
0
        {
12022
            // Keep applying until reaching NavId
12023
0
            NavApplyItemToResult(result);
12024
0
        }
12025
0
    }
12026
0
    else if (g.NavTabbingDir == 0)
12027
0
    {
12028
0
        if (can_stop && g.NavId == id)
12029
0
            NavMoveRequestResolveWithLastItem(result);
12030
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12031
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12032
0
    }
12033
60
}
12034
12035
bool ImGui::NavMoveRequestButNoResultYet()
12036
43.7k
{
12037
43.7k
    ImGuiContext& g = *GImGui;
12038
43.7k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12039
43.7k
}
12040
12041
// FIXME: ScoringRect is not set
12042
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12043
3.31k
{
12044
3.31k
    ImGuiContext& g = *GImGui;
12045
3.31k
    IM_ASSERT(g.NavWindow != NULL);
12046
12047
3.31k
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12048
222
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12049
12050
3.31k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12051
3.31k
    g.NavMoveDir = move_dir;
12052
3.31k
    g.NavMoveDirForDebug = move_dir;
12053
3.31k
    g.NavMoveClipDir = clip_dir;
12054
3.31k
    g.NavMoveFlags = move_flags;
12055
3.31k
    g.NavMoveScrollFlags = scroll_flags;
12056
3.31k
    g.NavMoveForwardToNextFrame = false;
12057
3.31k
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12058
3.31k
    g.NavMoveResultLocal.Clear();
12059
3.31k
    g.NavMoveResultLocalVisible.Clear();
12060
3.31k
    g.NavMoveResultOther.Clear();
12061
3.31k
    g.NavTabbingCounter = 0;
12062
3.31k
    g.NavTabbingResultFirst.Clear();
12063
3.31k
    NavUpdateAnyRequestFlag();
12064
3.31k
}
12065
12066
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12067
0
{
12068
0
    ImGuiContext& g = *GImGui;
12069
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12070
0
    NavApplyItemToResult(result);
12071
0
    NavUpdateAnyRequestFlag();
12072
0
}
12073
12074
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12075
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12076
0
{
12077
0
    ImGuiContext& g = *GImGui;
12078
0
    g.NavMoveScoringItems = false;
12079
0
    g.LastItemData.ID = tree_node_data->ID;
12080
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12081
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12082
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12083
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12084
0
    NavUpdateAnyRequestFlag();
12085
0
}
12086
12087
void ImGui::NavMoveRequestCancel()
12088
836
{
12089
836
    ImGuiContext& g = *GImGui;
12090
836
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12091
836
    NavUpdateAnyRequestFlag();
12092
836
}
12093
12094
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12095
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12096
0
{
12097
0
    ImGuiContext& g = *GImGui;
12098
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12099
0
    NavMoveRequestCancel();
12100
0
    g.NavMoveForwardToNextFrame = true;
12101
0
    g.NavMoveDir = move_dir;
12102
0
    g.NavMoveClipDir = clip_dir;
12103
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12104
0
    g.NavMoveScrollFlags = scroll_flags;
12105
0
}
12106
12107
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12108
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12109
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12110
0
{
12111
0
    ImGuiContext& g = *GImGui;
12112
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12113
12114
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12115
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12116
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12117
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12118
0
}
12119
12120
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12121
// This way we could find the last focused window among our children. It would be much less confusing this way?
12122
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12123
38.6k
{
12124
38.6k
    ImGuiWindow* parent = nav_window;
12125
64.7k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12126
26.1k
        parent = parent->ParentWindow;
12127
38.6k
    if (parent && parent != nav_window)
12128
26.1k
        parent->NavLastChildNavWindow = nav_window;
12129
38.6k
}
12130
12131
// Restore the last focused child.
12132
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12133
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12134
1
{
12135
1
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12136
0
        return window->NavLastChildNavWindow;
12137
1
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12138
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12139
0
            return tab->Window;
12140
1
    return window;
12141
1
}
12142
12143
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12144
0
{
12145
0
    ImGuiContext& g = *GImGui;
12146
0
    if (layer == ImGuiNavLayer_Main)
12147
0
    {
12148
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12149
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12150
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12151
0
        if (prev_nav_window)
12152
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12153
0
    }
12154
0
    ImGuiWindow* window = g.NavWindow;
12155
0
    if (window->NavLastIds[layer] != 0)
12156
0
    {
12157
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12158
0
    }
12159
0
    else
12160
0
    {
12161
0
        g.NavLayer = layer;
12162
0
        NavInitWindow(window, true);
12163
0
    }
12164
0
}
12165
12166
void ImGui::NavRestoreHighlightAfterMove()
12167
2.35k
{
12168
2.35k
    ImGuiContext& g = *GImGui;
12169
2.35k
    g.NavDisableHighlight = false;
12170
2.35k
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12171
2.35k
}
12172
12173
static inline void ImGui::NavUpdateAnyRequestFlag()
12174
85.1k
{
12175
85.1k
    ImGuiContext& g = *GImGui;
12176
85.1k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12177
85.1k
    if (g.NavAnyRequest)
12178
85.1k
        IM_ASSERT(g.NavWindow != NULL);
12179
85.1k
}
12180
12181
// This needs to be called before we submit any widget (aka in or before Begin)
12182
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12183
41
{
12184
    // FIXME: ChildWindow test here is wrong for docking
12185
41
    ImGuiContext& g = *GImGui;
12186
41
    IM_ASSERT(window == g.NavWindow);
12187
12188
41
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12189
0
    {
12190
0
        g.NavId = 0;
12191
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12192
0
        return;
12193
0
    }
12194
12195
41
    bool init_for_nav = false;
12196
41
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12197
41
        init_for_nav = true;
12198
41
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12199
41
    if (init_for_nav)
12200
41
    {
12201
41
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12202
41
        g.NavInitRequest = true;
12203
41
        g.NavInitRequestFromMove = false;
12204
41
        g.NavInitResult.ID = 0;
12205
41
        NavUpdateAnyRequestFlag();
12206
41
    }
12207
0
    else
12208
0
    {
12209
0
        g.NavId = window->NavLastIds[0];
12210
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12211
0
    }
12212
41
}
12213
12214
static ImVec2 ImGui::NavCalcPreferredRefPos()
12215
0
{
12216
0
    ImGuiContext& g = *GImGui;
12217
0
    ImGuiWindow* window = g.NavWindow;
12218
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12219
0
    {
12220
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12221
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12222
        // In theory we could move that +1.0f offset in OpenPopupEx()
12223
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12224
0
        return ImVec2(p.x + 1.0f, p.y);
12225
0
    }
12226
0
    else
12227
0
    {
12228
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12229
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12230
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12231
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12232
0
        {
12233
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12234
0
            rect_rel.Translate(window->Scroll - next_scroll);
12235
0
        }
12236
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12237
0
        ImGuiViewport* viewport = window->Viewport;
12238
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12239
0
    }
12240
0
}
12241
12242
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12243
0
{
12244
0
    ImGuiContext& g = *GImGui;
12245
0
    float repeat_delay, repeat_rate;
12246
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12247
12248
0
    ImGuiKey key_less, key_more;
12249
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12250
0
    {
12251
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12252
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12253
0
    }
12254
0
    else
12255
0
    {
12256
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12257
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12258
0
    }
12259
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12260
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12261
0
        amount = 0.0f;
12262
0
    return amount;
12263
0
}
12264
12265
static void ImGui::NavUpdate()
12266
69.6k
{
12267
69.6k
    ImGuiContext& g = *GImGui;
12268
69.6k
    ImGuiIO& io = g.IO;
12269
12270
69.6k
    io.WantSetMousePos = false;
12271
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12272
12273
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12274
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12275
69.6k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12276
69.6k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12277
69.6k
    if (nav_gamepad_active)
12278
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12279
0
            if (IsKeyDown(key))
12280
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12281
69.6k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12282
69.6k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12283
69.6k
    if (nav_keyboard_active)
12284
69.6k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12285
487k
            if (IsKeyDown(key))
12286
32.0k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12287
12288
    // Process navigation init request (select first/default focus)
12289
69.6k
    g.NavJustMovedToId = 0;
12290
69.6k
    if (g.NavInitResult.ID != 0)
12291
49
        NavInitRequestApplyResult();
12292
69.6k
    g.NavInitRequest = false;
12293
69.6k
    g.NavInitRequestFromMove = false;
12294
69.6k
    g.NavInitResult.ID = 0;
12295
12296
    // Process navigation move request
12297
69.6k
    if (g.NavMoveSubmitted)
12298
3.07k
        NavMoveRequestApplyResult();
12299
69.6k
    g.NavTabbingCounter = 0;
12300
69.6k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12301
12302
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12303
69.6k
    bool set_mouse_pos = false;
12304
69.6k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12305
2.20k
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12306
2.20k
            set_mouse_pos = true;
12307
69.6k
    g.NavMousePosDirty = false;
12308
69.6k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12309
12310
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12311
69.6k
    if (g.NavWindow)
12312
38.6k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12313
69.6k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12314
634
        g.NavWindow->NavLastChildNavWindow = NULL;
12315
12316
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12317
69.6k
    NavUpdateWindowing();
12318
12319
    // Set output flags for user application
12320
69.6k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12321
69.6k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12322
12323
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12324
69.6k
    NavUpdateCancelRequest();
12325
12326
    // Process manual activation request
12327
69.6k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12328
69.6k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12329
69.6k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12330
11.2k
    {
12331
11.2k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
12332
11.2k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
12333
11.2k
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_KeypadEnter))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
12334
11.2k
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, false) || IsKeyPressed(ImGuiKey_KeypadEnter, false))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
12335
11.2k
        if (g.ActiveId == 0 && activate_pressed)
12336
13
        {
12337
13
            g.NavActivateId = g.NavId;
12338
13
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12339
13
        }
12340
11.2k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12341
27
        {
12342
27
            g.NavActivateId = g.NavId;
12343
27
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12344
27
        }
12345
11.2k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12346
391
            g.NavActivateDownId = g.NavId;
12347
11.2k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12348
40
            g.NavActivatePressedId = g.NavId;
12349
11.2k
    }
12350
69.6k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12351
0
        g.NavDisableHighlight = true;
12352
69.6k
    if (g.NavActivateId != 0)
12353
69.6k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12354
12355
    // Process programmatic activation request
12356
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12357
69.6k
    if (g.NavNextActivateId != 0)
12358
0
    {
12359
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12360
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12361
0
    }
12362
69.6k
    g.NavNextActivateId = 0;
12363
12364
    // Process move requests
12365
69.6k
    NavUpdateCreateMoveRequest();
12366
69.6k
    if (g.NavMoveDir == ImGuiDir_None)
12367
66.5k
        NavUpdateCreateTabbingRequest();
12368
69.6k
    NavUpdateAnyRequestFlag();
12369
69.6k
    g.NavIdIsAlive = false;
12370
12371
    // Scrolling
12372
69.6k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12373
38.6k
    {
12374
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12375
38.6k
        ImGuiWindow* window = g.NavWindow;
12376
38.6k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12377
38.6k
        const ImGuiDir move_dir = g.NavMoveDir;
12378
38.6k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12379
1.15k
        {
12380
1.15k
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12381
537
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12382
1.15k
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12383
616
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12384
1.15k
        }
12385
12386
        // *Normal* Manual scroll with LStick
12387
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12388
38.6k
        if (nav_gamepad_active)
12389
0
        {
12390
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12391
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12392
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12393
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12394
0
            if (scroll_dir.y != 0.0f)
12395
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12396
0
        }
12397
38.6k
    }
12398
12399
    // Always prioritize mouse highlight if navigation is disabled
12400
69.6k
    if (!nav_keyboard_active && !nav_gamepad_active)
12401
0
    {
12402
0
        g.NavDisableHighlight = true;
12403
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12404
0
    }
12405
12406
    // Update mouse position if requested
12407
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12408
69.6k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12409
0
        TeleportMousePos(NavCalcPreferredRefPos());
12410
12411
    // [DEBUG]
12412
69.6k
    g.NavScoringDebugCount = 0;
12413
#if IMGUI_DEBUG_NAV_RECTS
12414
    if (ImGuiWindow* debug_window = g.NavWindow)
12415
    {
12416
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12417
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12418
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12419
    }
12420
#endif
12421
69.6k
}
12422
12423
void ImGui::NavInitRequestApplyResult()
12424
49
{
12425
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12426
49
    ImGuiContext& g = *GImGui;
12427
49
    if (!g.NavWindow)
12428
6
        return;
12429
12430
43
    ImGuiNavItemData* result = &g.NavInitResult;
12431
43
    if (g.NavId != result->ID)
12432
43
    {
12433
43
        g.NavJustMovedToId = result->ID;
12434
43
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12435
43
        g.NavJustMovedToKeyMods = 0;
12436
43
    }
12437
12438
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12439
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12440
43
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12441
43
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12442
43
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12443
43
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12444
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12445
43
    if (g.NavInitRequestFromMove)
12446
43
        NavRestoreHighlightAfterMove();
12447
43
}
12448
12449
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12450
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12451
3.09k
{
12452
    // Bias initial rect
12453
3.09k
    ImGuiContext& g = *GImGui;
12454
3.09k
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12455
12456
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12457
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12458
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12459
3.09k
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12460
3.09k
    {
12461
3.09k
        if (preferred_pos_rel.x == FLT_MAX)
12462
985
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12463
3.09k
        if (preferred_pos_rel.y == FLT_MAX)
12464
1.20k
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12465
3.09k
    }
12466
12467
    // Apply general bias on the other axis
12468
3.09k
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12469
2.30k
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12470
786
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12471
786
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12472
3.09k
}
12473
12474
void ImGui::NavUpdateCreateMoveRequest()
12475
69.6k
{
12476
69.6k
    ImGuiContext& g = *GImGui;
12477
69.6k
    ImGuiIO& io = g.IO;
12478
69.6k
    ImGuiWindow* window = g.NavWindow;
12479
69.6k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12480
69.6k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12481
12482
69.6k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12483
0
    {
12484
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12485
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12486
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12487
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12488
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12489
0
    }
12490
69.6k
    else
12491
69.6k
    {
12492
        // Initiate directional inputs request
12493
69.6k
        g.NavMoveDir = ImGuiDir_None;
12494
69.6k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12495
69.6k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12496
69.6k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12497
38.6k
        {
12498
38.6k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12499
38.6k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12500
38.6k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12501
38.6k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12502
38.6k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12503
38.6k
        }
12504
69.6k
        g.NavMoveClipDir = g.NavMoveDir;
12505
69.6k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12506
69.6k
    }
12507
12508
    // Update PageUp/PageDown/Home/End scroll
12509
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12510
69.6k
    float scoring_rect_offset_y = 0.0f;
12511
69.6k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12512
37.1k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12513
69.6k
    if (scoring_rect_offset_y != 0.0f)
12514
1.43k
    {
12515
1.43k
        g.NavScoringNoClipRect = window->InnerRect;
12516
1.43k
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12517
1.43k
    }
12518
12519
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12520
#if IMGUI_DEBUG_NAV_SCORING
12521
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12522
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12523
    if (io.KeyCtrl)
12524
    {
12525
        if (g.NavMoveDir == ImGuiDir_None)
12526
            g.NavMoveDir = g.NavMoveDirForDebug;
12527
        g.NavMoveClipDir = g.NavMoveDir;
12528
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12529
    }
12530
#endif
12531
12532
    // Submit
12533
69.6k
    g.NavMoveForwardToNextFrame = false;
12534
69.6k
    if (g.NavMoveDir != ImGuiDir_None)
12535
3.09k
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12536
12537
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12538
69.6k
    if (g.NavMoveSubmitted && g.NavId == 0)
12539
1.30k
    {
12540
1.30k
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12541
1.30k
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12542
1.30k
        g.NavInitResult.ID = 0;
12543
1.30k
        g.NavDisableHighlight = false;
12544
1.30k
    }
12545
12546
    // When using gamepad, we project the reference nav bounding box into window visible area.
12547
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12548
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12549
69.6k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12550
0
    {
12551
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12552
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12553
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12554
12555
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12556
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12557
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12558
12559
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12560
0
        {
12561
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12562
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12563
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12564
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12565
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12566
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12567
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12568
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12569
0
            g.NavId = 0;
12570
0
        }
12571
0
    }
12572
12573
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12574
69.6k
    ImRect scoring_rect;
12575
69.6k
    if (window != NULL)
12576
38.6k
    {
12577
38.6k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12578
38.6k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12579
38.6k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12580
38.6k
        if (g.NavMoveSubmitted)
12581
3.09k
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12582
38.6k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12583
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12584
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12585
38.6k
    }
12586
69.6k
    g.NavScoringRect = scoring_rect;
12587
69.6k
    g.NavScoringNoClipRect.Add(scoring_rect);
12588
69.6k
}
12589
12590
void ImGui::NavUpdateCreateTabbingRequest()
12591
66.5k
{
12592
66.5k
    ImGuiContext& g = *GImGui;
12593
66.5k
    ImGuiWindow* window = g.NavWindow;
12594
66.5k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12595
66.5k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12596
31.0k
        return;
12597
12598
35.5k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12599
35.5k
    if (!tab_pressed)
12600
35.3k
        return;
12601
12602
    // Initiate tabbing request
12603
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12604
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12605
222
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12606
222
    if (nav_keyboard_active)
12607
222
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12608
0
    else
12609
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12610
222
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12611
222
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12612
222
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12613
222
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12614
222
    g.NavTabbingCounter = -1;
12615
222
}
12616
12617
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12618
void ImGui::NavMoveRequestApplyResult()
12619
3.07k
{
12620
3.07k
    ImGuiContext& g = *GImGui;
12621
#if IMGUI_DEBUG_NAV_SCORING
12622
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12623
        return;
12624
#endif
12625
12626
    // Select which result to use
12627
3.07k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12628
12629
    // Tabbing forward wrap
12630
3.07k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12631
202
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12632
54
            result = &g.NavTabbingResultFirst;
12633
12634
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12635
3.07k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12636
3.07k
    if (result == NULL)
12637
1.68k
    {
12638
1.68k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12639
148
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12640
1.68k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12641
404
            NavRestoreHighlightAfterMove();
12642
1.68k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12643
1.68k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12644
1.68k
        return;
12645
1.68k
    }
12646
12647
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12648
1.39k
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12649
1.23k
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12650
0
            result = &g.NavMoveResultLocalVisible;
12651
12652
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12653
1.39k
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12654
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12655
0
            result = &g.NavMoveResultOther;
12656
1.39k
    IM_ASSERT(g.NavWindow && result->Window);
12657
12658
    // Scroll to keep newly navigated item fully into view.
12659
1.39k
    if (g.NavLayer == ImGuiNavLayer_Main)
12660
1.39k
    {
12661
1.39k
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12662
1.39k
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12663
12664
1.39k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12665
65
        {
12666
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12667
65
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12668
65
            SetScrollY(result->Window, scroll_target);
12669
65
        }
12670
1.39k
    }
12671
12672
1.39k
    if (g.NavWindow != result->Window)
12673
0
    {
12674
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12675
0
        g.NavWindow = result->Window;
12676
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12677
0
    }
12678
1.39k
    if (g.ActiveId != result->ID)
12679
1.39k
        ClearActiveID();
12680
12681
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12682
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12683
1.39k
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12684
1.23k
    {
12685
1.23k
        g.NavJustMovedToId = result->ID;
12686
1.23k
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12687
1.23k
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12688
1.23k
    }
12689
12690
    // Apply new NavID/Focus
12691
1.39k
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12692
1.39k
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12693
1.39k
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12694
1.39k
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12695
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12696
12697
    // Restore last preferred position for current axis
12698
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12699
1.39k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
12700
1.33k
    {
12701
1.33k
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12702
1.33k
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12703
1.33k
    }
12704
12705
    // Tabbing: Activates Inputable, otherwise only Focus
12706
1.39k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12707
54
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12708
12709
    // Activate
12710
1.39k
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12711
0
    {
12712
0
        g.NavNextActivateId = result->ID;
12713
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12714
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12715
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
12716
0
    }
12717
12718
    // Enable nav highlight
12719
1.39k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12720
1.39k
        NavRestoreHighlightAfterMove();
12721
1.39k
}
12722
12723
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12724
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12725
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12726
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12727
static void ImGui::NavUpdateCancelRequest()
12728
69.6k
{
12729
69.6k
    ImGuiContext& g = *GImGui;
12730
69.6k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12731
69.6k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12732
69.6k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12733
68.5k
        return;
12734
12735
1.12k
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12736
1.12k
    if (g.ActiveId != 0)
12737
0
    {
12738
0
        ClearActiveID();
12739
0
    }
12740
1.12k
    else if (g.NavLayer != ImGuiNavLayer_Main)
12741
0
    {
12742
        // Leave the "menu" layer
12743
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12744
0
        NavRestoreHighlightAfterMove();
12745
0
    }
12746
1.12k
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12747
511
    {
12748
        // Exit child window
12749
511
        ImGuiWindow* child_window = g.NavWindow;
12750
511
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12751
511
        IM_ASSERT(child_window->ChildId != 0);
12752
511
        ImRect child_rect = child_window->Rect();
12753
511
        FocusWindow(parent_window);
12754
511
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12755
511
        NavRestoreHighlightAfterMove();
12756
511
    }
12757
614
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12758
0
    {
12759
        // Close open popup/menu
12760
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12761
0
    }
12762
614
    else
12763
614
    {
12764
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12765
614
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12766
148
            g.NavWindow->NavLastIds[0] = 0;
12767
614
        g.NavId = 0;
12768
614
    }
12769
1.12k
}
12770
12771
// Handle PageUp/PageDown/Home/End keys
12772
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12773
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12774
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12775
static float ImGui::NavUpdatePageUpPageDown()
12776
37.1k
{
12777
37.1k
    ImGuiContext& g = *GImGui;
12778
37.1k
    ImGuiWindow* window = g.NavWindow;
12779
37.1k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12780
0
        return 0.0f;
12781
12782
37.1k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12783
37.1k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12784
37.1k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12785
37.1k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12786
37.1k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12787
27.8k
        return 0.0f;
12788
12789
9.30k
    if (g.NavLayer != ImGuiNavLayer_Main)
12790
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12791
12792
9.30k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12793
3.05k
    {
12794
        // Fallback manual-scroll when window has no navigable item
12795
3.05k
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12796
71
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12797
2.98k
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12798
578
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12799
2.40k
        else if (home_pressed)
12800
31
            SetScrollY(window, 0.0f);
12801
2.37k
        else if (end_pressed)
12802
157
            SetScrollY(window, window->ScrollMax.y);
12803
3.05k
    }
12804
6.24k
    else
12805
6.24k
    {
12806
6.24k
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12807
6.24k
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12808
6.24k
        float nav_scoring_rect_offset_y = 0.0f;
12809
6.24k
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12810
21
        {
12811
21
            nav_scoring_rect_offset_y = -page_offset_y;
12812
21
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12813
21
            g.NavMoveClipDir = ImGuiDir_Up;
12814
21
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12815
21
        }
12816
6.22k
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12817
1.42k
        {
12818
1.42k
            nav_scoring_rect_offset_y = +page_offset_y;
12819
1.42k
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12820
1.42k
            g.NavMoveClipDir = ImGuiDir_Down;
12821
1.42k
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12822
1.42k
        }
12823
4.80k
        else if (home_pressed)
12824
39
        {
12825
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12826
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12827
            // Preserve current horizontal position if we have any.
12828
39
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12829
39
            if (nav_rect_rel.IsInverted())
12830
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12831
39
            g.NavMoveDir = ImGuiDir_Down;
12832
39
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12833
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12834
39
        }
12835
4.76k
        else if (end_pressed)
12836
62
        {
12837
62
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12838
62
            if (nav_rect_rel.IsInverted())
12839
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12840
62
            g.NavMoveDir = ImGuiDir_Up;
12841
62
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12842
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12843
62
        }
12844
6.24k
        return nav_scoring_rect_offset_y;
12845
6.24k
    }
12846
3.05k
    return 0.0f;
12847
9.30k
}
12848
12849
static void ImGui::NavEndFrame()
12850
69.6k
{
12851
69.6k
    ImGuiContext& g = *GImGui;
12852
12853
    // Show CTRL+TAB list window
12854
69.6k
    if (g.NavWindowingTarget != NULL)
12855
0
        NavUpdateWindowingOverlay();
12856
12857
    // Perform wrap-around in menus
12858
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12859
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12860
69.6k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12861
0
        NavUpdateCreateWrappingRequest();
12862
69.6k
}
12863
12864
static void ImGui::NavUpdateCreateWrappingRequest()
12865
0
{
12866
0
    ImGuiContext& g = *GImGui;
12867
0
    ImGuiWindow* window = g.NavWindow;
12868
12869
0
    bool do_forward = false;
12870
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12871
0
    ImGuiDir clip_dir = g.NavMoveDir;
12872
12873
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12874
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12875
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12876
0
    {
12877
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12878
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12879
0
        {
12880
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12881
0
            clip_dir = ImGuiDir_Up;
12882
0
        }
12883
0
        do_forward = true;
12884
0
    }
12885
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12886
0
    {
12887
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12888
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12889
0
        {
12890
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12891
0
            clip_dir = ImGuiDir_Down;
12892
0
        }
12893
0
        do_forward = true;
12894
0
    }
12895
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12896
0
    {
12897
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12898
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12899
0
        {
12900
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12901
0
            clip_dir = ImGuiDir_Left;
12902
0
        }
12903
0
        do_forward = true;
12904
0
    }
12905
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12906
0
    {
12907
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12908
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12909
0
        {
12910
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12911
0
            clip_dir = ImGuiDir_Right;
12912
0
        }
12913
0
        do_forward = true;
12914
0
    }
12915
0
    if (!do_forward)
12916
0
        return;
12917
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12918
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12919
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12920
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12921
0
}
12922
12923
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12924
0
{
12925
0
    ImGuiContext& g = *GImGui;
12926
0
    IM_UNUSED(g);
12927
0
    int order = window->FocusOrder;
12928
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12929
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12930
0
    return order;
12931
0
}
12932
12933
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12934
0
{
12935
0
    ImGuiContext& g = *GImGui;
12936
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12937
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12938
0
            return g.WindowsFocusOrder[i];
12939
0
    return NULL;
12940
0
}
12941
12942
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12943
0
{
12944
0
    ImGuiContext& g = *GImGui;
12945
0
    IM_ASSERT(g.NavWindowingTarget);
12946
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12947
0
        return;
12948
12949
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12950
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12951
0
    if (!window_target)
12952
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12953
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12954
0
    {
12955
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12956
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12957
0
    }
12958
0
    g.NavWindowingToggleLayer = false;
12959
0
}
12960
12961
// Windowing management mode
12962
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12963
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12964
static void ImGui::NavUpdateWindowing()
12965
69.6k
{
12966
69.6k
    ImGuiContext& g = *GImGui;
12967
69.6k
    ImGuiIO& io = g.IO;
12968
12969
69.6k
    ImGuiWindow* apply_focus_window = NULL;
12970
69.6k
    bool apply_toggle_layer = false;
12971
12972
69.6k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12973
69.6k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12974
69.6k
    if (!allow_windowing)
12975
0
        g.NavWindowingTarget = NULL;
12976
12977
    // Fade out
12978
69.6k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12979
0
    {
12980
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12981
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12982
0
            g.NavWindowingTargetAnim = NULL;
12983
0
    }
12984
12985
    // Start CTRL+Tab or Square+L/R window selection
12986
69.6k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12987
69.6k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12988
69.6k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12989
69.6k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12990
69.6k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12991
69.6k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12992
69.6k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12993
69.6k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12994
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12995
0
        {
12996
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12997
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12998
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12999
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13000
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13001
13002
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13003
0
            if (keyboard_next_window || keyboard_prev_window)
13004
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13005
0
        }
13006
13007
    // Gamepad update
13008
69.6k
    g.NavWindowingTimer += io.DeltaTime;
13009
69.6k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13010
0
    {
13011
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13012
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13013
13014
        // Select window to focus
13015
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13016
0
        if (focus_change_dir != 0)
13017
0
        {
13018
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13019
0
            g.NavWindowingHighlightAlpha = 1.0f;
13020
0
        }
13021
13022
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13023
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13024
0
        {
13025
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13026
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13027
0
                apply_toggle_layer = true;
13028
0
            else if (!g.NavWindowingToggleLayer)
13029
0
                apply_focus_window = g.NavWindowingTarget;
13030
0
            g.NavWindowingTarget = NULL;
13031
0
        }
13032
0
    }
13033
13034
    // Keyboard: Focus
13035
69.6k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13036
0
    {
13037
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13038
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13039
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13040
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13041
0
        if (keyboard_next_window || keyboard_prev_window)
13042
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13043
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13044
0
            apply_focus_window = g.NavWindowingTarget;
13045
0
    }
13046
13047
    // Keyboard: Press and Release ALT to toggle menu layer
13048
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
13049
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
13050
69.6k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
13051
0
    {
13052
0
        g.NavWindowingToggleLayer = true;
13053
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
13054
0
    }
13055
69.6k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13056
0
    {
13057
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13058
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13059
        // We cancel toggling nav layer if an owner has claimed the key.
13060
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13061
0
            g.NavWindowingToggleLayer = false;
13062
13063
        // Apply layer toggle on release
13064
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13065
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
13066
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13067
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13068
0
                    apply_toggle_layer = true;
13069
0
        if (!IsKeyDown(ImGuiMod_Alt))
13070
0
            g.NavWindowingToggleLayer = false;
13071
0
    }
13072
13073
    // Move window
13074
69.6k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13075
0
    {
13076
0
        ImVec2 nav_move_dir;
13077
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13078
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13079
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13080
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13081
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13082
0
        {
13083
0
            const float NAV_MOVE_SPEED = 800.0f;
13084
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13085
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13086
0
            g.NavDisableMouseHover = true;
13087
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13088
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13089
0
            {
13090
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13091
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13092
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13093
0
            }
13094
0
        }
13095
0
    }
13096
13097
    // Apply final focus
13098
69.6k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13099
0
    {
13100
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13101
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13102
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13103
0
        ClearActiveID();
13104
0
        NavRestoreHighlightAfterMove();
13105
0
        ClosePopupsOverWindow(apply_focus_window, false);
13106
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13107
0
        apply_focus_window = g.NavWindow;
13108
0
        if (apply_focus_window->NavLastIds[0] == 0)
13109
0
            NavInitWindow(apply_focus_window, false);
13110
13111
        // If the window has ONLY a menu layer (no main layer), select it directly
13112
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13113
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13114
        // the target window as already been previewed once.
13115
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13116
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13117
        // won't be valid.
13118
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13119
0
            g.NavLayer = ImGuiNavLayer_Menu;
13120
13121
        // Request OS level focus
13122
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13123
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13124
0
    }
13125
69.6k
    if (apply_focus_window)
13126
0
        g.NavWindowingTarget = NULL;
13127
13128
    // Apply menu/layer toggle
13129
69.6k
    if (apply_toggle_layer && g.NavWindow)
13130
0
    {
13131
0
        ClearActiveID();
13132
13133
        // Move to parent menu if necessary
13134
0
        ImGuiWindow* new_nav_window = g.NavWindow;
13135
0
        while (new_nav_window->ParentWindow
13136
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13137
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13138
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13139
0
            new_nav_window = new_nav_window->ParentWindow;
13140
0
        if (new_nav_window != g.NavWindow)
13141
0
        {
13142
0
            ImGuiWindow* old_nav_window = g.NavWindow;
13143
0
            FocusWindow(new_nav_window);
13144
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13145
0
        }
13146
13147
        // Toggle layer
13148
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13149
0
        if (new_nav_layer != g.NavLayer)
13150
0
        {
13151
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13152
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13153
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13154
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13155
0
            NavRestoreLayer(new_nav_layer);
13156
0
            NavRestoreHighlightAfterMove();
13157
0
        }
13158
0
    }
13159
69.6k
}
13160
13161
// Window has already passed the IsWindowNavFocusable()
13162
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13163
0
{
13164
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13165
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13166
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13167
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13168
0
    if (window->DockNodeAsHost)
13169
0
        return "(Dock node)"; // Not normally shown to user.
13170
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13171
0
}
13172
13173
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13174
void ImGui::NavUpdateWindowingOverlay()
13175
0
{
13176
0
    ImGuiContext& g = *GImGui;
13177
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13178
13179
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13180
0
        return;
13181
13182
0
    if (g.NavWindowingListWindow == NULL)
13183
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13184
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13185
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13186
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13187
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13188
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13189
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13190
0
    {
13191
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13192
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13193
0
        if (!IsWindowNavFocusable(window))
13194
0
            continue;
13195
0
        const char* label = window->Name;
13196
0
        if (label == FindRenderedTextEnd(label))
13197
0
            label = GetFallbackWindowNameForWindowingList(window);
13198
0
        Selectable(label, g.NavWindowingTarget == window);
13199
0
    }
13200
0
    End();
13201
0
    PopStyleVar();
13202
0
}
13203
13204
13205
//-----------------------------------------------------------------------------
13206
// [SECTION] DRAG AND DROP
13207
//-----------------------------------------------------------------------------
13208
13209
bool ImGui::IsDragDropActive()
13210
0
{
13211
0
    ImGuiContext& g = *GImGui;
13212
0
    return g.DragDropActive;
13213
0
}
13214
13215
void ImGui::ClearDragDrop()
13216
234
{
13217
234
    ImGuiContext& g = *GImGui;
13218
234
    g.DragDropActive = false;
13219
234
    g.DragDropPayload.Clear();
13220
234
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13221
234
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13222
234
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13223
234
    g.DragDropAcceptFrameCount = -1;
13224
13225
234
    g.DragDropPayloadBufHeap.clear();
13226
234
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13227
234
}
13228
13229
bool ImGui::BeginTooltipHidden()
13230
0
{
13231
0
    ImGuiContext& g = *GImGui;
13232
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13233
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13234
0
    return ret;
13235
0
}
13236
13237
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13238
// If the item has an identifier:
13239
// - This assume/require the item to be activated (typically via ButtonBehavior).
13240
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13241
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13242
// If the item has no identifier:
13243
// - Currently always assume left mouse button.
13244
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13245
594
{
13246
594
    ImGuiContext& g = *GImGui;
13247
594
    ImGuiWindow* window = g.CurrentWindow;
13248
13249
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13250
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13251
594
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13252
13253
594
    bool source_drag_active = false;
13254
594
    ImGuiID source_id = 0;
13255
594
    ImGuiID source_parent_id = 0;
13256
594
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13257
594
    {
13258
594
        source_id = g.LastItemData.ID;
13259
594
        if (source_id != 0)
13260
594
        {
13261
            // Common path: items with ID
13262
594
            if (g.ActiveId != source_id)
13263
0
                return false;
13264
594
            if (g.ActiveIdMouseButton != -1)
13265
0
                mouse_button = g.ActiveIdMouseButton;
13266
594
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13267
0
                return false;
13268
594
            g.ActiveIdAllowOverlap = false;
13269
594
        }
13270
0
        else
13271
0
        {
13272
            // Uncommon path: items without ID
13273
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13274
0
                return false;
13275
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13276
0
                return false;
13277
13278
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13279
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13280
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13281
0
            {
13282
0
                IM_ASSERT(0);
13283
0
                return false;
13284
0
            }
13285
13286
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13287
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13288
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13289
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13290
            // Rely on keeping other window->LastItemXXX fields intact.
13291
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13292
0
            KeepAliveID(source_id);
13293
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13294
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13295
0
            {
13296
0
                SetActiveID(source_id, window);
13297
0
                FocusWindow(window);
13298
0
            }
13299
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13300
0
                g.ActiveIdAllowOverlap = is_hovered;
13301
0
        }
13302
594
        if (g.ActiveId != source_id)
13303
0
            return false;
13304
594
        source_parent_id = window->IDStack.back();
13305
594
        source_drag_active = IsMouseDragging(mouse_button);
13306
13307
        // Disable navigation and key inputs while dragging + cancel existing request if any
13308
594
        SetActiveIdUsingAllKeyboardKeys();
13309
594
    }
13310
0
    else
13311
0
    {
13312
0
        window = NULL;
13313
0
        source_id = ImHashStr("#SourceExtern");
13314
0
        source_drag_active = true;
13315
0
    }
13316
13317
594
    if (source_drag_active)
13318
425
    {
13319
425
        if (!g.DragDropActive)
13320
117
        {
13321
117
            IM_ASSERT(source_id != 0);
13322
117
            ClearDragDrop();
13323
117
            ImGuiPayload& payload = g.DragDropPayload;
13324
117
            payload.SourceId = source_id;
13325
117
            payload.SourceParentId = source_parent_id;
13326
117
            g.DragDropActive = true;
13327
117
            g.DragDropSourceFlags = flags;
13328
117
            g.DragDropMouseButton = mouse_button;
13329
117
            if (payload.SourceId == g.ActiveId)
13330
117
                g.ActiveIdNoClearOnFocusLoss = true;
13331
117
        }
13332
425
        g.DragDropSourceFrameCount = g.FrameCount;
13333
425
        g.DragDropWithinSource = true;
13334
13335
425
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13336
0
        {
13337
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13338
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13339
0
            bool ret;
13340
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13341
0
                ret = BeginTooltipHidden();
13342
0
            else
13343
0
                ret = BeginTooltip();
13344
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13345
0
            IM_UNUSED(ret);
13346
0
        }
13347
13348
425
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13349
425
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13350
13351
425
        return true;
13352
425
    }
13353
169
    return false;
13354
594
}
13355
13356
void ImGui::EndDragDropSource()
13357
425
{
13358
425
    ImGuiContext& g = *GImGui;
13359
425
    IM_ASSERT(g.DragDropActive);
13360
425
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13361
13362
425
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13363
0
        EndTooltip();
13364
13365
    // Discard the drag if have not called SetDragDropPayload()
13366
425
    if (g.DragDropPayload.DataFrameCount == -1)
13367
0
        ClearDragDrop();
13368
425
    g.DragDropWithinSource = false;
13369
425
}
13370
13371
// Use 'cond' to choose to submit payload on drag start or every frame
13372
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13373
425
{
13374
425
    ImGuiContext& g = *GImGui;
13375
425
    ImGuiPayload& payload = g.DragDropPayload;
13376
425
    if (cond == 0)
13377
425
        cond = ImGuiCond_Always;
13378
13379
425
    IM_ASSERT(type != NULL);
13380
425
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13381
425
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13382
425
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13383
425
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13384
13385
425
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13386
425
    {
13387
        // Copy payload
13388
425
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13389
425
        g.DragDropPayloadBufHeap.resize(0);
13390
425
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13391
0
        {
13392
            // Store in heap
13393
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13394
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13395
0
            memcpy(payload.Data, data, data_size);
13396
0
        }
13397
425
        else if (data_size > 0)
13398
425
        {
13399
            // Store locally
13400
425
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13401
425
            payload.Data = g.DragDropPayloadBufLocal;
13402
425
            memcpy(payload.Data, data, data_size);
13403
425
        }
13404
0
        else
13405
0
        {
13406
0
            payload.Data = NULL;
13407
0
        }
13408
425
        payload.DataSize = (int)data_size;
13409
425
    }
13410
425
    payload.DataFrameCount = g.FrameCount;
13411
13412
    // Return whether the payload has been accepted
13413
425
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13414
425
}
13415
13416
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13417
777
{
13418
777
    ImGuiContext& g = *GImGui;
13419
777
    if (!g.DragDropActive)
13420
0
        return false;
13421
13422
777
    ImGuiWindow* window = g.CurrentWindow;
13423
777
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13424
777
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13425
692
        return false;
13426
85
    IM_ASSERT(id != 0);
13427
85
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13428
0
        return false;
13429
85
    if (window->SkipItems)
13430
0
        return false;
13431
13432
85
    IM_ASSERT(g.DragDropWithinTarget == false);
13433
85
    g.DragDropTargetRect = bb;
13434
85
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
13435
85
    g.DragDropTargetId = id;
13436
85
    g.DragDropWithinTarget = true;
13437
85
    return true;
13438
85
}
13439
13440
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13441
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13442
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13443
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13444
bool ImGui::BeginDragDropTarget()
13445
0
{
13446
0
    ImGuiContext& g = *GImGui;
13447
0
    if (!g.DragDropActive)
13448
0
        return false;
13449
13450
0
    ImGuiWindow* window = g.CurrentWindow;
13451
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13452
0
        return false;
13453
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13454
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13455
0
        return false;
13456
13457
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13458
0
    ImGuiID id = g.LastItemData.ID;
13459
0
    if (id == 0)
13460
0
    {
13461
0
        id = window->GetIDFromRectangle(display_rect);
13462
0
        KeepAliveID(id);
13463
0
    }
13464
0
    if (g.DragDropPayload.SourceId == id)
13465
0
        return false;
13466
13467
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13468
0
    g.DragDropTargetRect = display_rect;
13469
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13470
0
    g.DragDropTargetId = id;
13471
0
    g.DragDropWithinTarget = true;
13472
0
    return true;
13473
0
}
13474
13475
bool ImGui::IsDragDropPayloadBeingAccepted()
13476
239
{
13477
239
    ImGuiContext& g = *GImGui;
13478
239
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13479
239
}
13480
13481
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13482
85
{
13483
85
    ImGuiContext& g = *GImGui;
13484
85
    ImGuiPayload& payload = g.DragDropPayload;
13485
85
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13486
85
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13487
85
    if (type != NULL && !payload.IsDataType(type))
13488
0
        return NULL;
13489
13490
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13491
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13492
85
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13493
85
    ImRect r = g.DragDropTargetRect;
13494
85
    float r_surface = r.GetWidth() * r.GetHeight();
13495
85
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13496
0
        return NULL;
13497
13498
85
    g.DragDropAcceptFlags = flags;
13499
85
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13500
85
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13501
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13502
13503
    // Render default drop visuals
13504
85
    payload.Preview = was_accepted_previously;
13505
85
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13506
85
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13507
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
13508
13509
85
    g.DragDropAcceptFrameCount = g.FrameCount;
13510
85
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13511
85
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13512
0
        return NULL;
13513
13514
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13515
85
    return &payload;
13516
85
}
13517
13518
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13519
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13520
0
{
13521
0
    ImGuiContext& g = *GImGui;
13522
0
    ImGuiWindow* window = g.CurrentWindow;
13523
0
    ImRect bb_display = bb;
13524
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13525
0
    bb_display.Expand(3.5f);
13526
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13527
0
    if (push_clip_rect)
13528
0
        window->DrawList->PushClipRectFullScreen();
13529
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13530
0
    if (push_clip_rect)
13531
0
        window->DrawList->PopClipRect();
13532
0
}
13533
13534
const ImGuiPayload* ImGui::GetDragDropPayload()
13535
0
{
13536
0
    ImGuiContext& g = *GImGui;
13537
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13538
0
}
13539
13540
void ImGui::EndDragDropTarget()
13541
85
{
13542
85
    ImGuiContext& g = *GImGui;
13543
85
    IM_ASSERT(g.DragDropActive);
13544
85
    IM_ASSERT(g.DragDropWithinTarget);
13545
85
    g.DragDropWithinTarget = false;
13546
13547
    // Clear drag and drop state payload right after delivery
13548
85
    if (g.DragDropPayload.Delivery)
13549
0
        ClearDragDrop();
13550
85
}
13551
13552
//-----------------------------------------------------------------------------
13553
// [SECTION] LOGGING/CAPTURING
13554
//-----------------------------------------------------------------------------
13555
// All text output from the interface can be captured into tty/file/clipboard.
13556
// By default, tree nodes are automatically opened during logging.
13557
//-----------------------------------------------------------------------------
13558
13559
// Pass text data straight to log (without being displayed)
13560
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13561
0
{
13562
0
    if (g.LogFile)
13563
0
    {
13564
0
        g.LogBuffer.Buf.resize(0);
13565
0
        g.LogBuffer.appendfv(fmt, args);
13566
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13567
0
    }
13568
0
    else
13569
0
    {
13570
0
        g.LogBuffer.appendfv(fmt, args);
13571
0
    }
13572
0
}
13573
13574
void ImGui::LogText(const char* fmt, ...)
13575
0
{
13576
0
    ImGuiContext& g = *GImGui;
13577
0
    if (!g.LogEnabled)
13578
0
        return;
13579
13580
0
    va_list args;
13581
0
    va_start(args, fmt);
13582
0
    LogTextV(g, fmt, args);
13583
0
    va_end(args);
13584
0
}
13585
13586
void ImGui::LogTextV(const char* fmt, va_list args)
13587
0
{
13588
0
    ImGuiContext& g = *GImGui;
13589
0
    if (!g.LogEnabled)
13590
0
        return;
13591
13592
0
    LogTextV(g, fmt, args);
13593
0
}
13594
13595
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13596
// We split text into individual lines to add current tree level padding
13597
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13598
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13599
0
{
13600
0
    ImGuiContext& g = *GImGui;
13601
0
    ImGuiWindow* window = g.CurrentWindow;
13602
13603
0
    const char* prefix = g.LogNextPrefix;
13604
0
    const char* suffix = g.LogNextSuffix;
13605
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13606
13607
0
    if (!text_end)
13608
0
        text_end = FindRenderedTextEnd(text, text_end);
13609
13610
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13611
0
    if (ref_pos)
13612
0
        g.LogLinePosY = ref_pos->y;
13613
0
    if (log_new_line)
13614
0
    {
13615
0
        LogText(IM_NEWLINE);
13616
0
        g.LogLineFirstItem = true;
13617
0
    }
13618
13619
0
    if (prefix)
13620
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13621
13622
    // Re-adjust padding if we have popped out of our starting depth
13623
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13624
0
        g.LogDepthRef = window->DC.TreeDepth;
13625
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13626
13627
0
    const char* text_remaining = text;
13628
0
    for (;;)
13629
0
    {
13630
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13631
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13632
0
        const char* line_start = text_remaining;
13633
0
        const char* line_end = ImStreolRange(line_start, text_end);
13634
0
        const bool is_last_line = (line_end == text_end);
13635
0
        if (line_start != line_end || !is_last_line)
13636
0
        {
13637
0
            const int line_length = (int)(line_end - line_start);
13638
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13639
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13640
0
            g.LogLineFirstItem = false;
13641
0
            if (*line_end == '\n')
13642
0
            {
13643
0
                LogText(IM_NEWLINE);
13644
0
                g.LogLineFirstItem = true;
13645
0
            }
13646
0
        }
13647
0
        if (is_last_line)
13648
0
            break;
13649
0
        text_remaining = line_end + 1;
13650
0
    }
13651
13652
0
    if (suffix)
13653
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13654
0
}
13655
13656
// Start logging/capturing text output
13657
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13658
0
{
13659
0
    ImGuiContext& g = *GImGui;
13660
0
    ImGuiWindow* window = g.CurrentWindow;
13661
0
    IM_ASSERT(g.LogEnabled == false);
13662
0
    IM_ASSERT(g.LogFile == NULL);
13663
0
    IM_ASSERT(g.LogBuffer.empty());
13664
0
    g.LogEnabled = true;
13665
0
    g.LogType = type;
13666
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13667
0
    g.LogDepthRef = window->DC.TreeDepth;
13668
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13669
0
    g.LogLinePosY = FLT_MAX;
13670
0
    g.LogLineFirstItem = true;
13671
0
}
13672
13673
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13674
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13675
0
{
13676
0
    ImGuiContext& g = *GImGui;
13677
0
    g.LogNextPrefix = prefix;
13678
0
    g.LogNextSuffix = suffix;
13679
0
}
13680
13681
void ImGui::LogToTTY(int auto_open_depth)
13682
0
{
13683
0
    ImGuiContext& g = *GImGui;
13684
0
    if (g.LogEnabled)
13685
0
        return;
13686
0
    IM_UNUSED(auto_open_depth);
13687
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13688
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13689
0
    g.LogFile = stdout;
13690
0
#endif
13691
0
}
13692
13693
// Start logging/capturing text output to given file
13694
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13695
0
{
13696
0
    ImGuiContext& g = *GImGui;
13697
0
    if (g.LogEnabled)
13698
0
        return;
13699
13700
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13701
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13702
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13703
0
    if (!filename)
13704
0
        filename = g.IO.LogFilename;
13705
0
    if (!filename || !filename[0])
13706
0
        return;
13707
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13708
0
    if (!f)
13709
0
    {
13710
0
        IM_ASSERT(0);
13711
0
        return;
13712
0
    }
13713
13714
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13715
0
    g.LogFile = f;
13716
0
}
13717
13718
// Start logging/capturing text output to clipboard
13719
void ImGui::LogToClipboard(int auto_open_depth)
13720
0
{
13721
0
    ImGuiContext& g = *GImGui;
13722
0
    if (g.LogEnabled)
13723
0
        return;
13724
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13725
0
}
13726
13727
void ImGui::LogToBuffer(int auto_open_depth)
13728
0
{
13729
0
    ImGuiContext& g = *GImGui;
13730
0
    if (g.LogEnabled)
13731
0
        return;
13732
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13733
0
}
13734
13735
void ImGui::LogFinish()
13736
139k
{
13737
139k
    ImGuiContext& g = *GImGui;
13738
139k
    if (!g.LogEnabled)
13739
139k
        return;
13740
13741
0
    LogText(IM_NEWLINE);
13742
0
    switch (g.LogType)
13743
0
    {
13744
0
    case ImGuiLogType_TTY:
13745
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13746
0
        fflush(g.LogFile);
13747
0
#endif
13748
0
        break;
13749
0
    case ImGuiLogType_File:
13750
0
        ImFileClose(g.LogFile);
13751
0
        break;
13752
0
    case ImGuiLogType_Buffer:
13753
0
        break;
13754
0
    case ImGuiLogType_Clipboard:
13755
0
        if (!g.LogBuffer.empty())
13756
0
            SetClipboardText(g.LogBuffer.begin());
13757
0
        break;
13758
0
    case ImGuiLogType_None:
13759
0
        IM_ASSERT(0);
13760
0
        break;
13761
0
    }
13762
13763
0
    g.LogEnabled = false;
13764
0
    g.LogType = ImGuiLogType_None;
13765
0
    g.LogFile = NULL;
13766
0
    g.LogBuffer.clear();
13767
0
}
13768
13769
// Helper to display logging buttons
13770
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13771
void ImGui::LogButtons()
13772
0
{
13773
0
    ImGuiContext& g = *GImGui;
13774
13775
0
    PushID("LogButtons");
13776
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13777
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13778
#else
13779
    const bool log_to_tty = false;
13780
#endif
13781
0
    const bool log_to_file = Button("Log To File"); SameLine();
13782
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13783
0
    PushTabStop(false);
13784
0
    SetNextItemWidth(80.0f);
13785
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13786
0
    PopTabStop();
13787
0
    PopID();
13788
13789
    // Start logging at the end of the function so that the buttons don't appear in the log
13790
0
    if (log_to_tty)
13791
0
        LogToTTY();
13792
0
    if (log_to_file)
13793
0
        LogToFile();
13794
0
    if (log_to_clipboard)
13795
0
        LogToClipboard();
13796
0
}
13797
13798
13799
//-----------------------------------------------------------------------------
13800
// [SECTION] SETTINGS
13801
//-----------------------------------------------------------------------------
13802
// - UpdateSettings() [Internal]
13803
// - MarkIniSettingsDirty() [Internal]
13804
// - FindSettingsHandler() [Internal]
13805
// - ClearIniSettings() [Internal]
13806
// - LoadIniSettingsFromDisk()
13807
// - LoadIniSettingsFromMemory()
13808
// - SaveIniSettingsToDisk()
13809
// - SaveIniSettingsToMemory()
13810
//-----------------------------------------------------------------------------
13811
// - CreateNewWindowSettings() [Internal]
13812
// - FindWindowSettingsByID() [Internal]
13813
// - FindWindowSettingsByWindow() [Internal]
13814
// - ClearWindowSettings() [Internal]
13815
// - WindowSettingsHandler_***() [Internal]
13816
//-----------------------------------------------------------------------------
13817
13818
// Called by NewFrame()
13819
void ImGui::UpdateSettings()
13820
69.6k
{
13821
    // Load settings on first frame (if not explicitly loaded manually before)
13822
69.6k
    ImGuiContext& g = *GImGui;
13823
69.6k
    if (!g.SettingsLoaded)
13824
1
    {
13825
1
        IM_ASSERT(g.SettingsWindows.empty());
13826
1
        if (g.IO.IniFilename)
13827
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13828
1
        g.SettingsLoaded = true;
13829
1
    }
13830
13831
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13832
69.6k
    if (g.SettingsDirtyTimer > 0.0f)
13833
11.1k
    {
13834
11.1k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13835
11.1k
        if (g.SettingsDirtyTimer <= 0.0f)
13836
37
        {
13837
37
            if (g.IO.IniFilename != NULL)
13838
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13839
37
            else
13840
37
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13841
37
            g.SettingsDirtyTimer = 0.0f;
13842
37
        }
13843
11.1k
    }
13844
69.6k
}
13845
13846
void ImGui::MarkIniSettingsDirty()
13847
0
{
13848
0
    ImGuiContext& g = *GImGui;
13849
0
    if (g.SettingsDirtyTimer <= 0.0f)
13850
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13851
0
}
13852
13853
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13854
47.9k
{
13855
47.9k
    ImGuiContext& g = *GImGui;
13856
47.9k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13857
296
        if (g.SettingsDirtyTimer <= 0.0f)
13858
37
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13859
47.9k
}
13860
13861
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13862
2
{
13863
2
    ImGuiContext& g = *GImGui;
13864
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13865
2
    g.SettingsHandlers.push_back(*handler);
13866
2
}
13867
13868
void ImGui::RemoveSettingsHandler(const char* type_name)
13869
0
{
13870
0
    ImGuiContext& g = *GImGui;
13871
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13872
0
        g.SettingsHandlers.erase(handler);
13873
0
}
13874
13875
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13876
2
{
13877
2
    ImGuiContext& g = *GImGui;
13878
2
    const ImGuiID type_hash = ImHashStr(type_name);
13879
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13880
1
        if (handler.TypeHash == type_hash)
13881
0
            return &handler;
13882
2
    return NULL;
13883
2
}
13884
13885
// Clear all settings (windows, tables, docking etc.)
13886
void ImGui::ClearIniSettings()
13887
0
{
13888
0
    ImGuiContext& g = *GImGui;
13889
0
    g.SettingsIniData.clear();
13890
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13891
0
        if (handler.ClearAllFn != NULL)
13892
0
            handler.ClearAllFn(&g, &handler);
13893
0
}
13894
13895
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13896
0
{
13897
0
    size_t file_data_size = 0;
13898
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13899
0
    if (!file_data)
13900
0
        return;
13901
0
    if (file_data_size > 0)
13902
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13903
0
    IM_FREE(file_data);
13904
0
}
13905
13906
// Zero-tolerance, no error reporting, cheap .ini parsing
13907
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13908
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13909
0
{
13910
0
    ImGuiContext& g = *GImGui;
13911
0
    IM_ASSERT(g.Initialized);
13912
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13913
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13914
13915
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13916
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13917
0
    if (ini_size == 0)
13918
0
        ini_size = strlen(ini_data);
13919
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13920
0
    char* const buf = g.SettingsIniData.Buf.Data;
13921
0
    char* const buf_end = buf + ini_size;
13922
0
    memcpy(buf, ini_data, ini_size);
13923
0
    buf_end[0] = 0;
13924
13925
    // Call pre-read handlers
13926
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13927
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13928
0
        if (handler.ReadInitFn != NULL)
13929
0
            handler.ReadInitFn(&g, &handler);
13930
13931
0
    void* entry_data = NULL;
13932
0
    ImGuiSettingsHandler* entry_handler = NULL;
13933
13934
0
    char* line_end = NULL;
13935
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13936
0
    {
13937
        // Skip new lines markers, then find end of the line
13938
0
        while (*line == '\n' || *line == '\r')
13939
0
            line++;
13940
0
        line_end = line;
13941
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13942
0
            line_end++;
13943
0
        line_end[0] = 0;
13944
0
        if (line[0] == ';')
13945
0
            continue;
13946
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13947
0
        {
13948
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13949
0
            line_end[-1] = 0;
13950
0
            const char* name_end = line_end - 1;
13951
0
            const char* type_start = line + 1;
13952
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13953
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13954
0
            if (!type_end || !name_start)
13955
0
                continue;
13956
0
            *type_end = 0; // Overwrite first ']'
13957
0
            name_start++;  // Skip second '['
13958
0
            entry_handler = FindSettingsHandler(type_start);
13959
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13960
0
        }
13961
0
        else if (entry_handler != NULL && entry_data != NULL)
13962
0
        {
13963
            // Let type handler parse the line
13964
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13965
0
        }
13966
0
    }
13967
0
    g.SettingsLoaded = true;
13968
13969
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13970
0
    memcpy(buf, ini_data, ini_size);
13971
13972
    // Call post-read handlers
13973
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13974
0
        if (handler.ApplyAllFn != NULL)
13975
0
            handler.ApplyAllFn(&g, &handler);
13976
0
}
13977
13978
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13979
0
{
13980
0
    ImGuiContext& g = *GImGui;
13981
0
    g.SettingsDirtyTimer = 0.0f;
13982
0
    if (!ini_filename)
13983
0
        return;
13984
13985
0
    size_t ini_data_size = 0;
13986
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13987
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13988
0
    if (!f)
13989
0
        return;
13990
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13991
0
    ImFileClose(f);
13992
0
}
13993
13994
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13995
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13996
0
{
13997
0
    ImGuiContext& g = *GImGui;
13998
0
    g.SettingsDirtyTimer = 0.0f;
13999
0
    g.SettingsIniData.Buf.resize(0);
14000
0
    g.SettingsIniData.Buf.push_back(0);
14001
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14002
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14003
0
    if (out_size)
14004
0
        *out_size = (size_t)g.SettingsIniData.size();
14005
0
    return g.SettingsIniData.c_str();
14006
0
}
14007
14008
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14009
0
{
14010
0
    ImGuiContext& g = *GImGui;
14011
14012
0
    if (g.IO.ConfigDebugIniSettings == false)
14013
0
    {
14014
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14015
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14016
0
        if (const char* p = strstr(name, "###"))
14017
0
            name = p;
14018
0
    }
14019
0
    const size_t name_len = strlen(name);
14020
14021
    // Allocate chunk
14022
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14023
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14024
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14025
0
    settings->ID = ImHashStr(name, name_len);
14026
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14027
14028
0
    return settings;
14029
0
}
14030
14031
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14032
// This is called once per window .ini entry + once per newly instantiated window.
14033
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14034
2
{
14035
2
    ImGuiContext& g = *GImGui;
14036
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14037
0
        if (settings->ID == id && !settings->WantDelete)
14038
0
            return settings;
14039
2
    return NULL;
14040
2
}
14041
14042
// This is faster if you are holding on a Window already as we don't need to perform a search.
14043
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14044
2
{
14045
2
    ImGuiContext& g = *GImGui;
14046
2
    if (window->SettingsOffset != -1)
14047
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14048
2
    return FindWindowSettingsByID(window->ID);
14049
2
}
14050
14051
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14052
void ImGui::ClearWindowSettings(const char* name)
14053
0
{
14054
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14055
0
    ImGuiContext& g = *GImGui;
14056
0
    ImGuiWindow* window = FindWindowByName(name);
14057
0
    if (window != NULL)
14058
0
    {
14059
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14060
0
        InitOrLoadWindowSettings(window, NULL);
14061
0
        if (window->DockId != 0)
14062
0
            DockContextProcessUndockWindow(&g, window, true);
14063
0
    }
14064
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14065
0
        settings->WantDelete = true;
14066
0
}
14067
14068
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14069
0
{
14070
0
    ImGuiContext& g = *ctx;
14071
0
    for (ImGuiWindow* window : g.Windows)
14072
0
        window->SettingsOffset = -1;
14073
0
    g.SettingsWindows.clear();
14074
0
}
14075
14076
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14077
0
{
14078
0
    ImGuiID id = ImHashStr(name);
14079
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14080
0
    if (settings)
14081
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14082
0
    else
14083
0
        settings = ImGui::CreateNewWindowSettings(name);
14084
0
    settings->ID = id;
14085
0
    settings->WantApply = true;
14086
0
    return (void*)settings;
14087
0
}
14088
14089
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14090
0
{
14091
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14092
0
    int x, y;
14093
0
    int i;
14094
0
    ImU32 u1;
14095
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14096
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14097
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14098
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14099
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14100
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14101
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14102
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14103
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14104
0
}
14105
14106
// Apply to existing windows (if any)
14107
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14108
0
{
14109
0
    ImGuiContext& g = *ctx;
14110
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14111
0
        if (settings->WantApply)
14112
0
        {
14113
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14114
0
                ApplyWindowSettings(window, settings);
14115
0
            settings->WantApply = false;
14116
0
        }
14117
0
}
14118
14119
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14120
0
{
14121
    // Gather data from windows that were active during this session
14122
    // (if a window wasn't opened in this session we preserve its settings)
14123
0
    ImGuiContext& g = *ctx;
14124
0
    for (ImGuiWindow* window : g.Windows)
14125
0
    {
14126
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14127
0
            continue;
14128
14129
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14130
0
        if (!settings)
14131
0
        {
14132
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14133
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14134
0
        }
14135
0
        IM_ASSERT(settings->ID == window->ID);
14136
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14137
0
        settings->Size = ImVec2ih(window->SizeFull);
14138
0
        settings->ViewportId = window->ViewportId;
14139
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14140
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14141
0
        settings->DockId = window->DockId;
14142
0
        settings->ClassId = window->WindowClass.ClassId;
14143
0
        settings->DockOrder = window->DockOrder;
14144
0
        settings->Collapsed = window->Collapsed;
14145
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14146
0
        settings->WantDelete = false;
14147
0
    }
14148
14149
    // Write to text buffer
14150
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14151
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14152
0
    {
14153
0
        if (settings->WantDelete)
14154
0
            continue;
14155
0
        const char* settings_name = settings->GetName();
14156
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14157
0
        if (settings->IsChild)
14158
0
        {
14159
0
            buf->appendf("IsChild=1\n");
14160
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14161
0
        }
14162
0
        else
14163
0
        {
14164
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14165
0
            {
14166
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14167
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14168
0
            }
14169
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14170
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14171
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14172
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14173
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14174
0
            if (settings->DockId != 0)
14175
0
            {
14176
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14177
0
                if (settings->DockOrder == -1)
14178
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14179
0
                else
14180
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14181
0
                if (settings->ClassId != 0)
14182
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14183
0
            }
14184
0
        }
14185
0
        buf->append("\n");
14186
0
    }
14187
0
}
14188
14189
14190
//-----------------------------------------------------------------------------
14191
// [SECTION] LOCALIZATION
14192
//-----------------------------------------------------------------------------
14193
14194
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14195
1
{
14196
1
    ImGuiContext& g = *GImGui;
14197
12
    for (int n = 0; n < count; n++)
14198
11
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14199
1
}
14200
14201
14202
//-----------------------------------------------------------------------------
14203
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14204
//-----------------------------------------------------------------------------
14205
// - GetMainViewport()
14206
// - FindViewportByID()
14207
// - FindViewportByPlatformHandle()
14208
// - SetCurrentViewport() [Internal]
14209
// - SetWindowViewport() [Internal]
14210
// - GetWindowAlwaysWantOwnViewport() [Internal]
14211
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14212
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14213
// - TranslateWindowsInViewport() [Internal]
14214
// - ScaleWindowsInViewport() [Internal]
14215
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14216
// - UpdateViewportsNewFrame() [Internal]
14217
// - UpdateViewportsEndFrame() [Internal]
14218
// - AddUpdateViewport() [Internal]
14219
// - WindowSelectViewport() [Internal]
14220
// - WindowSyncOwnedViewport() [Internal]
14221
// - UpdatePlatformWindows()
14222
// - RenderPlatformWindowsDefault()
14223
// - FindPlatformMonitorForPos() [Internal]
14224
// - FindPlatformMonitorForRect() [Internal]
14225
// - UpdateViewportPlatformMonitor() [Internal]
14226
// - DestroyPlatformWindow() [Internal]
14227
// - DestroyPlatformWindows()
14228
//-----------------------------------------------------------------------------
14229
14230
ImGuiViewport* ImGui::GetMainViewport()
14231
188k
{
14232
188k
    ImGuiContext& g = *GImGui;
14233
188k
    return g.Viewports[0];
14234
188k
}
14235
14236
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14237
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14238
69.6k
{
14239
69.6k
    ImGuiContext& g = *GImGui;
14240
69.6k
    for (ImGuiViewportP* viewport : g.Viewports)
14241
69.6k
        if (viewport->ID == id)
14242
69.6k
            return viewport;
14243
0
    return NULL;
14244
69.6k
}
14245
14246
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14247
0
{
14248
0
    ImGuiContext& g = *GImGui;
14249
0
    for (ImGuiViewportP* viewport : g.Viewports)
14250
0
        if (viewport->PlatformHandle == platform_handle)
14251
0
            return viewport;
14252
0
    return NULL;
14253
0
}
14254
14255
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14256
376k
{
14257
376k
    ImGuiContext& g = *GImGui;
14258
376k
    (void)current_window;
14259
14260
376k
    if (viewport)
14261
307k
        viewport->LastFrameActive = g.FrameCount;
14262
376k
    if (g.CurrentViewport == viewport)
14263
237k
        return;
14264
139k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14265
139k
    g.CurrentViewport = viewport;
14266
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14267
14268
    // Notify platform layer of viewport changes
14269
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14270
139k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14271
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14272
139k
}
14273
14274
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14275
188k
{
14276
    // Abandon viewport
14277
188k
    if (window->ViewportOwned && window->Viewport->Window == window)
14278
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14279
14280
188k
    window->Viewport = viewport;
14281
188k
    window->ViewportId = viewport->ID;
14282
188k
    window->ViewportOwned = (viewport->Window == window);
14283
188k
}
14284
14285
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14286
0
{
14287
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14288
0
    ImGuiContext& g = *GImGui;
14289
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14290
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14291
0
            if (!window->DockIsActive)
14292
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14293
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14294
0
                        return true;
14295
0
    return false;
14296
0
}
14297
14298
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14299
0
{
14300
0
    ImGuiContext& g = *GImGui;
14301
0
    if (window->Viewport == viewport)
14302
0
        return false;
14303
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14304
0
        return false;
14305
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14306
0
        return false;
14307
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14308
0
        return false;
14309
0
    if (GetWindowAlwaysWantOwnViewport(window))
14310
0
        return false;
14311
14312
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14313
0
    for (ImGuiWindow* window_behind : g.Windows)
14314
0
    {
14315
0
        if (window_behind == window)
14316
0
            break;
14317
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14318
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14319
0
                return false;
14320
0
    }
14321
14322
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14323
0
    ImGuiViewportP* old_viewport = window->Viewport;
14324
0
    if (window->ViewportOwned)
14325
0
        for (int n = 0; n < g.Windows.Size; n++)
14326
0
            if (g.Windows[n]->Viewport == old_viewport)
14327
0
                SetWindowViewport(g.Windows[n], viewport);
14328
0
    SetWindowViewport(window, viewport);
14329
0
    BringWindowToDisplayFront(window);
14330
14331
0
    return true;
14332
0
}
14333
14334
// FIXME: handle 0 to N host viewports
14335
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14336
0
{
14337
0
    ImGuiContext& g = *GImGui;
14338
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14339
0
}
14340
14341
// Translate Dear ImGui windows when a Host Viewport has been moved
14342
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14343
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14344
0
{
14345
0
    ImGuiContext& g = *GImGui;
14346
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14347
14348
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14349
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14350
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14351
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14352
    // and so the window will appear to teleport when releasing the mouse.
14353
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14354
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14355
0
    ImVec2 delta_pos = new_pos - old_pos;
14356
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14357
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14358
0
            TranslateWindow(window, delta_pos);
14359
0
}
14360
14361
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14362
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14363
0
{
14364
0
    ImGuiContext& g = *GImGui;
14365
0
    if (viewport->Window)
14366
0
    {
14367
0
        ScaleWindow(viewport->Window, scale);
14368
0
    }
14369
0
    else
14370
0
    {
14371
0
        for (ImGuiWindow* window : g.Windows)
14372
0
            if (window->Viewport == viewport)
14373
0
                ScaleWindow(window, scale);
14374
0
    }
14375
0
}
14376
14377
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14378
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14379
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14380
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14381
0
{
14382
0
    ImGuiContext& g = *GImGui;
14383
0
    ImGuiViewportP* best_candidate = NULL;
14384
0
    for (ImGuiViewportP* viewport : g.Viewports)
14385
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14386
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14387
0
                best_candidate = viewport;
14388
0
    return best_candidate;
14389
0
}
14390
14391
// Update viewports and monitor infos
14392
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14393
static void ImGui::UpdateViewportsNewFrame()
14394
69.6k
{
14395
69.6k
    ImGuiContext& g = *GImGui;
14396
69.6k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14397
14398
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14399
    // Update Focused status
14400
69.6k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14401
69.6k
    if (viewports_enabled)
14402
0
    {
14403
0
        ImGuiViewportP* focused_viewport = NULL;
14404
0
        for (ImGuiViewportP* viewport : g.Viewports)
14405
0
        {
14406
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14407
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14408
0
            {
14409
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14410
0
                if (is_minimized)
14411
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14412
0
                else
14413
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14414
0
            }
14415
14416
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14417
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14418
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14419
0
            {
14420
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14421
0
                if (is_focused)
14422
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14423
0
                else
14424
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14425
0
                if (is_focused)
14426
0
                    focused_viewport = viewport;
14427
0
            }
14428
0
        }
14429
14430
        // Focused viewport has changed?
14431
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14432
0
        {
14433
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14434
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14435
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14436
14437
            // Store a tag so we can infer z-order easily from all our windows
14438
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14439
            // will keep the front most stamp instead of losing it back to their parent viewport.
14440
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14441
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14442
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14443
14444
            // Focus associated dear imgui window
14445
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14446
            // - if focus didn't happen because we destroyed another window (#6462)
14447
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14448
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14449
0
            if (apply_imgui_focus_on_focused_viewport)
14450
0
            {
14451
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14452
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14453
0
                if (focused_viewport->Window != NULL)
14454
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14455
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14456
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14457
0
                else
14458
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14459
0
            }
14460
0
        }
14461
0
        if (focused_viewport)
14462
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14463
0
    }
14464
14465
    // Create/update main viewport with current platform position.
14466
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14467
69.6k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14468
69.6k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14469
69.6k
    IM_ASSERT(main_viewport->Window == NULL);
14470
69.6k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14471
69.6k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14472
69.6k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14473
0
    {
14474
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14475
0
        main_viewport_size = main_viewport->Size;
14476
0
    }
14477
69.6k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14478
14479
69.6k
    g.CurrentDpiScale = 0.0f;
14480
69.6k
    g.CurrentViewport = NULL;
14481
69.6k
    g.MouseViewport = NULL;
14482
139k
    for (int n = 0; n < g.Viewports.Size; n++)
14483
69.6k
    {
14484
69.6k
        ImGuiViewportP* viewport = g.Viewports[n];
14485
69.6k
        viewport->Idx = n;
14486
14487
        // Erase unused viewports
14488
69.6k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14489
0
        {
14490
0
            DestroyViewport(viewport);
14491
0
            n--;
14492
0
            continue;
14493
0
        }
14494
14495
69.6k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14496
69.6k
        if (viewports_enabled)
14497
0
        {
14498
            // Update Position and Size (from Platform Window to ImGui) if requested.
14499
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14500
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14501
0
            {
14502
                // Viewport->WorkPos and WorkSize will be updated below
14503
0
                if (viewport->PlatformRequestMove)
14504
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14505
0
                if (viewport->PlatformRequestResize)
14506
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14507
0
            }
14508
0
        }
14509
14510
        // Update/copy monitor info
14511
69.6k
        UpdateViewportPlatformMonitor(viewport);
14512
14513
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14514
69.6k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14515
69.6k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14516
69.6k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14517
69.6k
        viewport->UpdateWorkRect();
14518
14519
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14520
69.6k
        viewport->Alpha = 1.0f;
14521
14522
        // Translate Dear ImGui windows when a Host Viewport has been moved
14523
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14524
69.6k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14525
69.6k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14526
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14527
14528
        // Update DPI scale
14529
69.6k
        float new_dpi_scale;
14530
69.6k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14531
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14532
69.6k
        else if (viewport->PlatformMonitor != -1)
14533
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14534
69.6k
        else
14535
69.6k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14536
69.6k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14537
0
        {
14538
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14539
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14540
0
                ScaleWindowsInViewport(viewport, scale_factor);
14541
            //if (viewport == GetMainViewport())
14542
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14543
14544
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14545
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14546
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14547
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14548
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14549
0
        }
14550
69.6k
        viewport->DpiScale = new_dpi_scale;
14551
69.6k
    }
14552
14553
    // Update fallback monitor
14554
69.6k
    if (g.PlatformIO.Monitors.Size == 0)
14555
69.6k
    {
14556
69.6k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14557
69.6k
        monitor->MainPos = main_viewport->Pos;
14558
69.6k
        monitor->MainSize = main_viewport->Size;
14559
69.6k
        monitor->WorkPos = main_viewport->WorkPos;
14560
69.6k
        monitor->WorkSize = main_viewport->WorkSize;
14561
69.6k
        monitor->DpiScale = main_viewport->DpiScale;
14562
69.6k
    }
14563
14564
69.6k
    if (!viewports_enabled)
14565
69.6k
    {
14566
69.6k
        g.MouseViewport = main_viewport;
14567
69.6k
        return;
14568
69.6k
    }
14569
14570
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14571
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14572
0
    ImGuiViewportP* viewport_hovered = NULL;
14573
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14574
0
    {
14575
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14576
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14577
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14578
0
    }
14579
0
    else
14580
0
    {
14581
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14582
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14583
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14584
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14585
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14586
0
    }
14587
0
    if (viewport_hovered != NULL)
14588
0
        g.MouseLastHoveredViewport = viewport_hovered;
14589
0
    else if (g.MouseLastHoveredViewport == NULL)
14590
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14591
14592
    // Update mouse reference viewport
14593
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14594
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14595
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14596
0
        g.MouseViewport = g.MovingWindow->Viewport;
14597
0
    else
14598
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14599
14600
    // When dragging something, always refer to the last hovered viewport.
14601
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14602
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14603
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14604
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14605
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14606
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14607
0
        viewport_hovered = g.MouseLastHoveredViewport;
14608
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14609
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14610
0
            g.MouseViewport = viewport_hovered;
14611
14612
0
    IM_ASSERT(g.MouseViewport != NULL);
14613
0
}
14614
14615
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14616
static void ImGui::UpdateViewportsEndFrame()
14617
69.6k
{
14618
69.6k
    ImGuiContext& g = *GImGui;
14619
69.6k
    g.PlatformIO.Viewports.resize(0);
14620
139k
    for (int i = 0; i < g.Viewports.Size; i++)
14621
69.6k
    {
14622
69.6k
        ImGuiViewportP* viewport = g.Viewports[i];
14623
69.6k
        viewport->LastPos = viewport->Pos;
14624
69.6k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14625
0
            if (i > 0) // Always include main viewport in the list
14626
0
                continue;
14627
69.6k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14628
0
            continue;
14629
69.6k
        if (i > 0)
14630
69.6k
            IM_ASSERT(viewport->Window != NULL);
14631
69.6k
        g.PlatformIO.Viewports.push_back(viewport);
14632
69.6k
    }
14633
69.6k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14634
69.6k
}
14635
14636
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14637
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14638
69.6k
{
14639
69.6k
    ImGuiContext& g = *GImGui;
14640
69.6k
    IM_ASSERT(id != 0);
14641
14642
69.6k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14643
69.6k
    if (window != NULL)
14644
0
    {
14645
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14646
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14647
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14648
0
            flags |= ImGuiViewportFlags_NoInputs;
14649
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14650
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14651
0
    }
14652
14653
69.6k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14654
69.6k
    if (viewport)
14655
69.6k
    {
14656
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14657
69.6k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14658
69.6k
            viewport->Pos = pos;
14659
69.6k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14660
69.6k
            viewport->Size = size;
14661
69.6k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14662
69.6k
    }
14663
0
    else
14664
0
    {
14665
        // New viewport
14666
0
        viewport = IM_NEW(ImGuiViewportP)();
14667
0
        viewport->ID = id;
14668
0
        viewport->Idx = g.Viewports.Size;
14669
0
        viewport->Pos = viewport->LastPos = pos;
14670
0
        viewport->Size = size;
14671
0
        viewport->Flags = flags;
14672
0
        UpdateViewportPlatformMonitor(viewport);
14673
0
        g.Viewports.push_back(viewport);
14674
0
        g.ViewportCreatedCount++;
14675
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14676
14677
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14678
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14679
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14680
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14681
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14682
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14683
14684
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14685
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14686
0
        if (viewport->PlatformMonitor != -1)
14687
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14688
0
    }
14689
14690
69.6k
    viewport->Window = window;
14691
69.6k
    viewport->LastFrameActive = g.FrameCount;
14692
69.6k
    viewport->UpdateWorkRect();
14693
69.6k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14694
14695
69.6k
    if (window != NULL)
14696
0
        window->ViewportOwned = true;
14697
14698
69.6k
    return viewport;
14699
69.6k
}
14700
14701
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14702
0
{
14703
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14704
0
    ImGuiContext& g = *GImGui;
14705
0
    for (ImGuiWindow* window : g.Windows)
14706
0
    {
14707
0
        if (window->Viewport != viewport)
14708
0
            continue;
14709
0
        window->Viewport = NULL;
14710
0
        window->ViewportOwned = false;
14711
0
    }
14712
0
    if (viewport == g.MouseLastHoveredViewport)
14713
0
        g.MouseLastHoveredViewport = NULL;
14714
14715
    // Destroy
14716
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14717
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14718
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14719
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14720
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14721
0
    IM_DELETE(viewport);
14722
0
}
14723
14724
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14725
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14726
188k
{
14727
188k
    ImGuiContext& g = *GImGui;
14728
188k
    ImGuiWindowFlags flags = window->Flags;
14729
188k
    window->ViewportAllowPlatformMonitorExtend = -1;
14730
14731
    // Restore main viewport if multi-viewport is not supported by the backend
14732
188k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14733
188k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14734
188k
    {
14735
188k
        SetWindowViewport(window, main_viewport);
14736
188k
        return;
14737
188k
    }
14738
0
    window->ViewportOwned = false;
14739
14740
    // Appearing popups reset their viewport so they can inherit again
14741
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14742
0
    {
14743
0
        window->Viewport = NULL;
14744
0
        window->ViewportId = 0;
14745
0
    }
14746
14747
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14748
0
    {
14749
        // By default inherit from parent window
14750
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14751
0
            window->Viewport = window->ParentWindow->Viewport;
14752
14753
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14754
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14755
0
        {
14756
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14757
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14758
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14759
0
        }
14760
0
    }
14761
14762
0
    bool lock_viewport = false;
14763
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14764
0
    {
14765
        // Code explicitly request a viewport
14766
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14767
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14768
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
14769
0
        {
14770
0
            window->Viewport->Window = window;
14771
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
14772
0
        }
14773
0
        lock_viewport = true;
14774
0
    }
14775
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14776
0
    {
14777
        // Always inherit viewport from parent window
14778
0
        if (window->DockNode && window->DockNode->HostWindow)
14779
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14780
0
        window->Viewport = window->ParentWindow->Viewport;
14781
0
    }
14782
0
    else if (window->DockNode && window->DockNode->HostWindow)
14783
0
    {
14784
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14785
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14786
0
    }
14787
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14788
0
    {
14789
0
        window->Viewport = g.MouseViewport;
14790
0
    }
14791
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14792
0
    {
14793
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14794
0
    }
14795
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14796
0
    {
14797
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14798
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14799
0
    }
14800
0
    else
14801
0
    {
14802
        // Merge into host viewport?
14803
        // We cannot test window->ViewportOwned as it set lower in the function.
14804
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14805
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14806
0
        if (try_to_merge_into_host_viewport)
14807
0
            UpdateTryMergeWindowIntoHostViewports(window);
14808
0
    }
14809
14810
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14811
0
    if (window->Viewport == NULL)
14812
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14813
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14814
14815
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14816
0
    if (!lock_viewport)
14817
0
    {
14818
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14819
0
        {
14820
            // We need to take account of the possibility that mouse may become invalid.
14821
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14822
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14823
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14824
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14825
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14826
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14827
0
            else
14828
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14829
0
        }
14830
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14831
0
        {
14832
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14833
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14834
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14835
0
            {
14836
                // Steal/transfer ownership
14837
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14838
0
                window->Viewport->Window = window;
14839
0
                window->Viewport->ID = window->ID;
14840
0
                window->Viewport->LastNameHash = 0;
14841
0
            }
14842
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14843
0
            {
14844
                // New viewport
14845
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14846
0
            }
14847
0
        }
14848
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14849
0
        {
14850
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14851
            // Child windows are kept contained within their parent.
14852
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14853
0
        }
14854
0
    }
14855
14856
    // Update flags
14857
0
    window->ViewportOwned = (window == window->Viewport->Window);
14858
0
    window->ViewportId = window->Viewport->ID;
14859
14860
    // If the OS window has a title bar, hide our imgui title bar
14861
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14862
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14863
0
}
14864
14865
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14866
0
{
14867
0
    ImGuiContext& g = *GImGui;
14868
14869
0
    bool viewport_rect_changed = false;
14870
14871
    // Synchronize window --> viewport in most situations
14872
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14873
0
    if (window->Viewport->PlatformRequestMove)
14874
0
    {
14875
0
        window->Pos = window->Viewport->Pos;
14876
0
        MarkIniSettingsDirty(window);
14877
0
    }
14878
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14879
0
    {
14880
0
        viewport_rect_changed = true;
14881
0
        window->Viewport->Pos = window->Pos;
14882
0
    }
14883
14884
0
    if (window->Viewport->PlatformRequestResize)
14885
0
    {
14886
0
        window->Size = window->SizeFull = window->Viewport->Size;
14887
0
        MarkIniSettingsDirty(window);
14888
0
    }
14889
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14890
0
    {
14891
0
        viewport_rect_changed = true;
14892
0
        window->Viewport->Size = window->Size;
14893
0
    }
14894
0
    window->Viewport->UpdateWorkRect();
14895
14896
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14897
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14898
0
    if (viewport_rect_changed)
14899
0
        UpdateViewportPlatformMonitor(window->Viewport);
14900
14901
    // Update common viewport flags
14902
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14903
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14904
0
    ImGuiWindowFlags window_flags = window->Flags;
14905
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14906
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14907
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14908
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14909
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14910
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14911
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14912
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14913
14914
    // Not correct to set modal as topmost because:
14915
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14916
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14917
    //if (flags & ImGuiWindowFlags_Modal)
14918
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14919
14920
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14921
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14922
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14923
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14924
0
    if (is_short_lived_floating_window && !is_modal)
14925
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14926
14927
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14928
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14929
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14930
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14931
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14932
14933
    // We can also tell the backend that clearing the platform window won't be necessary,
14934
    // as our window background is filling the viewport and we have disabled BgAlpha.
14935
    // FIXME: Work on support for per-viewport transparency (#2766)
14936
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14937
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14938
14939
0
    window->Viewport->Flags = viewport_flags;
14940
14941
    // Update parent viewport ID
14942
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14943
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14944
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14945
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14946
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14947
0
    else
14948
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14949
0
}
14950
14951
// Called by user at the end of the main loop, after EndFrame()
14952
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14953
void ImGui::UpdatePlatformWindows()
14954
0
{
14955
0
    ImGuiContext& g = *GImGui;
14956
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14957
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14958
0
    g.FrameCountPlatformEnded = g.FrameCount;
14959
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14960
0
        return;
14961
14962
    // Create/resize/destroy platform windows to match each active viewport.
14963
    // Skip the main viewport (index 0), which is always fully handled by the application!
14964
0
    for (int i = 1; i < g.Viewports.Size; i++)
14965
0
    {
14966
0
        ImGuiViewportP* viewport = g.Viewports[i];
14967
14968
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14969
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14970
0
        bool destroy_platform_window = false;
14971
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14972
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14973
0
        if (destroy_platform_window)
14974
0
        {
14975
0
            DestroyPlatformWindow(viewport);
14976
0
            continue;
14977
0
        }
14978
14979
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14980
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14981
0
            continue;
14982
14983
        // Create window
14984
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14985
0
        if (is_new_platform_window)
14986
0
        {
14987
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14988
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14989
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14990
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14991
0
            g.PlatformWindowsCreatedCount++;
14992
0
            viewport->LastNameHash = 0;
14993
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14994
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14995
0
            viewport->PlatformWindowCreated = true;
14996
0
        }
14997
14998
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14999
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15000
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15001
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15002
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15003
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15004
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15005
0
        viewport->LastPlatformPos = viewport->Pos;
15006
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15007
15008
        // Update title bar (if it changed)
15009
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15010
0
        {
15011
0
            const char* title_begin = window_for_title->Name;
15012
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15013
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15014
0
            if (viewport->LastNameHash != title_hash)
15015
0
            {
15016
0
                char title_end_backup_c = *title_end;
15017
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15018
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15019
0
                *title_end = title_end_backup_c;
15020
0
                viewport->LastNameHash = title_hash;
15021
0
            }
15022
0
        }
15023
15024
        // Update alpha (if it changed)
15025
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15026
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15027
0
        viewport->LastAlpha = viewport->Alpha;
15028
15029
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15030
0
        if (g.PlatformIO.Platform_UpdateWindow)
15031
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15032
15033
0
        if (is_new_platform_window)
15034
0
        {
15035
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15036
0
            if (g.FrameCount < 3)
15037
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15038
15039
            // Show window
15040
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15041
15042
            // Even without focus, we assume the window becomes front-most.
15043
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15044
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15045
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15046
0
        }
15047
15048
        // Clear request flags
15049
0
        viewport->ClearRequestFlags();
15050
0
    }
15051
0
}
15052
15053
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15054
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15055
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15056
//
15057
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15058
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15059
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15060
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15061
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15062
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15063
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15064
//
15065
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15066
0
{
15067
    // Skip the main viewport (index 0), which is always fully handled by the application!
15068
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15069
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15070
0
    {
15071
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15072
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15073
0
            continue;
15074
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15075
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15076
0
    }
15077
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15078
0
    {
15079
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15080
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15081
0
            continue;
15082
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15083
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15084
0
    }
15085
0
}
15086
15087
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15088
0
{
15089
0
    ImGuiContext& g = *GImGui;
15090
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15091
0
    {
15092
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15093
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15094
0
            return monitor_n;
15095
0
    }
15096
0
    return -1;
15097
0
}
15098
15099
// Search for the monitor with the largest intersection area with the given rectangle
15100
// We generally try to avoid searching loops but the monitor count should be very small here
15101
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15102
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15103
69.6k
{
15104
69.6k
    ImGuiContext& g = *GImGui;
15105
15106
69.6k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15107
69.6k
    if (monitor_count <= 1)
15108
69.6k
        return monitor_count - 1;
15109
15110
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15111
    // This is necessary for tooltips which always resize down to zero at first.
15112
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15113
0
    int best_monitor_n = -1;
15114
0
    float best_monitor_surface = 0.001f;
15115
15116
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15117
0
    {
15118
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15119
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15120
0
        if (monitor_rect.Contains(rect))
15121
0
            return monitor_n;
15122
0
        ImRect overlapping_rect = rect;
15123
0
        overlapping_rect.ClipWithFull(monitor_rect);
15124
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15125
0
        if (overlapping_surface < best_monitor_surface)
15126
0
            continue;
15127
0
        best_monitor_surface = overlapping_surface;
15128
0
        best_monitor_n = monitor_n;
15129
0
    }
15130
0
    return best_monitor_n;
15131
0
}
15132
15133
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15134
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15135
69.6k
{
15136
69.6k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15137
69.6k
}
15138
15139
// Return value is always != NULL, but don't hold on it across frames.
15140
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15141
0
{
15142
0
    ImGuiContext& g = *GImGui;
15143
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15144
0
    int monitor_idx = viewport->PlatformMonitor;
15145
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15146
0
        return &g.PlatformIO.Monitors[monitor_idx];
15147
0
    return &g.FallbackMonitor;
15148
0
}
15149
15150
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15151
0
{
15152
0
    ImGuiContext& g = *GImGui;
15153
0
    if (viewport->PlatformWindowCreated)
15154
0
    {
15155
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15156
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15157
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15158
0
        if (g.PlatformIO.Platform_DestroyWindow)
15159
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15160
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15161
15162
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15163
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15164
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15165
0
            viewport->PlatformWindowCreated = false;
15166
0
    }
15167
0
    else
15168
0
    {
15169
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15170
0
    }
15171
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15172
0
    viewport->ClearRequestFlags();
15173
0
}
15174
15175
void ImGui::DestroyPlatformWindows()
15176
0
{
15177
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15178
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15179
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15180
    // code to operator a consistent manner.
15181
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15182
    // crashing if it doesn't have data stored.
15183
0
    ImGuiContext& g = *GImGui;
15184
0
    for (ImGuiViewportP* viewport : g.Viewports)
15185
0
        DestroyPlatformWindow(viewport);
15186
0
}
15187
15188
15189
//-----------------------------------------------------------------------------
15190
// [SECTION] DOCKING
15191
//-----------------------------------------------------------------------------
15192
// Docking: Internal Types
15193
// Docking: Forward Declarations
15194
// Docking: ImGuiDockContext
15195
// Docking: ImGuiDockContext Docking/Undocking functions
15196
// Docking: ImGuiDockNode
15197
// Docking: ImGuiDockNode Tree manipulation functions
15198
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15199
// Docking: Builder Functions
15200
// Docking: Begin/End Support Functions (called from Begin/End)
15201
// Docking: Settings
15202
//-----------------------------------------------------------------------------
15203
15204
//-----------------------------------------------------------------------------
15205
// Typical Docking call flow: (root level is generally public API):
15206
//-----------------------------------------------------------------------------
15207
// - NewFrame()                               new dear imgui frame
15208
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15209
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15210
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15211
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15212
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15213
//    | - DockContextProcessDock()            - process one docking request
15214
//    | - DockNodeUpdate()
15215
//    |   - DockNodeUpdateForRootNode()
15216
//    |     - DockNodeUpdateFlagsAndCollapse()
15217
//    |     - DockNodeFindInfo()
15218
//    |   - destroy unused node or tab bar
15219
//    |   - create dock node host window
15220
//    |      - Begin() etc.
15221
//    |   - DockNodeStartMouseMovingWindow()
15222
//    |   - DockNodeTreeUpdatePosSize()
15223
//    |   - DockNodeTreeUpdateSplitter()
15224
//    |   - draw node background
15225
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15226
//    |     - DockNodeAddTabBar()
15227
//    |     - DockNodeWindowMenuUpdate()
15228
//    |     - DockNodeCalcTabBarLayout()
15229
//    |     - BeginTabBarEx()
15230
//    |     - TabItemEx() calls
15231
//    |     - EndTabBar()
15232
//    |   - BeginDockableDragDropTarget()
15233
//    |      - DockNodeUpdate()               - recurse into child nodes...
15234
//-----------------------------------------------------------------------------
15235
// - DockSpace()                              user submit a dockspace into a window
15236
//    | Begin(Child)                          - create a child window
15237
//    | DockNodeUpdate()                      - call main dock node update function
15238
//    | End(Child)
15239
//    | ItemSize()
15240
//-----------------------------------------------------------------------------
15241
// - Begin()
15242
//    | BeginDocked()
15243
//    | BeginDockableDragDropSource()
15244
//    | BeginDockableDragDropTarget()
15245
//    | - DockNodePreviewDockRender()
15246
//-----------------------------------------------------------------------------
15247
// - EndFrame()
15248
//    | DockContextEndFrame()
15249
//-----------------------------------------------------------------------------
15250
15251
//-----------------------------------------------------------------------------
15252
// Docking: Internal Types
15253
//-----------------------------------------------------------------------------
15254
// - ImGuiDockRequestType
15255
// - ImGuiDockRequest
15256
// - ImGuiDockPreviewData
15257
// - ImGuiDockNodeSettings
15258
// - ImGuiDockContext
15259
//-----------------------------------------------------------------------------
15260
15261
enum ImGuiDockRequestType
15262
{
15263
    ImGuiDockRequestType_None = 0,
15264
    ImGuiDockRequestType_Dock,
15265
    ImGuiDockRequestType_Undock,
15266
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15267
};
15268
15269
struct ImGuiDockRequest
15270
{
15271
    ImGuiDockRequestType    Type;
15272
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15273
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15274
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15275
    ImGuiDir                DockSplitDir;
15276
    float                   DockSplitRatio;
15277
    bool                    DockSplitOuter;
15278
    ImGuiWindow*            UndockTargetWindow;
15279
    ImGuiDockNode*          UndockTargetNode;
15280
15281
    ImGuiDockRequest()
15282
0
    {
15283
0
        Type = ImGuiDockRequestType_None;
15284
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15285
0
        DockTargetNode = UndockTargetNode = NULL;
15286
0
        DockSplitDir = ImGuiDir_None;
15287
0
        DockSplitRatio = 0.5f;
15288
0
        DockSplitOuter = false;
15289
0
    }
15290
};
15291
15292
struct ImGuiDockPreviewData
15293
{
15294
    ImGuiDockNode   FutureNode;
15295
    bool            IsDropAllowed;
15296
    bool            IsCenterAvailable;
15297
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15298
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15299
    ImGuiDockNode*  SplitNode;
15300
    ImGuiDir        SplitDir;
15301
    float           SplitRatio;
15302
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15303
15304
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15305
};
15306
15307
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15308
struct ImGuiDockNodeSettings
15309
{
15310
    ImGuiID             ID;
15311
    ImGuiID             ParentNodeId;
15312
    ImGuiID             ParentWindowId;
15313
    ImGuiID             SelectedTabId;
15314
    signed char         SplitAxis;
15315
    char                Depth;
15316
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15317
    ImVec2ih            Pos;
15318
    ImVec2ih            Size;
15319
    ImVec2ih            SizeRef;
15320
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15321
};
15322
15323
//-----------------------------------------------------------------------------
15324
// Docking: Forward Declarations
15325
//-----------------------------------------------------------------------------
15326
15327
namespace ImGui
15328
{
15329
    // ImGuiDockContext
15330
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15331
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15332
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15333
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15334
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15335
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15336
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15337
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15338
15339
    // ImGuiDockNode
15340
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15341
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15342
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15343
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15344
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15345
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15346
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15347
    static void             DockNodeUpdate(ImGuiDockNode* node);
15348
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15349
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15350
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15351
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15352
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15353
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15354
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15355
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15356
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15357
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15358
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15359
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15360
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15361
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15362
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15363
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15364
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15365
15366
    // ImGuiDockNode tree manipulations
15367
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15368
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15369
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15370
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15371
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15372
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15373
15374
    // Settings
15375
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15376
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15377
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15378
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15379
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15380
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15381
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15382
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15383
}
15384
15385
//-----------------------------------------------------------------------------
15386
// Docking: ImGuiDockContext
15387
//-----------------------------------------------------------------------------
15388
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15389
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15390
// At boot time only, we run a simple GC to remove nodes that have no references.
15391
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15392
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15393
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15394
//-----------------------------------------------------------------------------
15395
// - DockContextInitialize()
15396
// - DockContextShutdown()
15397
// - DockContextClearNodes()
15398
// - DockContextRebuildNodes()
15399
// - DockContextNewFrameUpdateUndocking()
15400
// - DockContextNewFrameUpdateDocking()
15401
// - DockContextEndFrame()
15402
// - DockContextFindNodeByID()
15403
// - DockContextBindNodeToWindow()
15404
// - DockContextGenNodeID()
15405
// - DockContextAddNode()
15406
// - DockContextRemoveNode()
15407
// - ImGuiDockContextPruneNodeData
15408
// - DockContextPruneUnusedSettingsNodes()
15409
// - DockContextBuildNodesFromSettings()
15410
// - DockContextBuildAddWindowsToNodes()
15411
//-----------------------------------------------------------------------------
15412
15413
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15414
1
{
15415
1
    ImGuiContext& g = *ctx;
15416
15417
    // Add .ini handle for persistent docking data
15418
1
    ImGuiSettingsHandler ini_handler;
15419
1
    ini_handler.TypeName = "Docking";
15420
1
    ini_handler.TypeHash = ImHashStr("Docking");
15421
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15422
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15423
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15424
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15425
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15426
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15427
1
    g.SettingsHandlers.push_back(ini_handler);
15428
15429
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15430
1
}
15431
15432
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15433
0
{
15434
0
    ImGuiDockContext* dc = &ctx->DockContext;
15435
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15436
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15437
0
            IM_DELETE(node);
15438
0
}
15439
15440
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15441
0
{
15442
0
    IM_UNUSED(ctx);
15443
0
    IM_ASSERT(ctx == GImGui);
15444
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15445
0
    DockBuilderRemoveNodeChildNodes(root_id);
15446
0
}
15447
15448
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15449
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15450
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15451
0
{
15452
0
    ImGuiContext& g = *ctx;
15453
0
    ImGuiDockContext* dc = &ctx->DockContext;
15454
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15455
0
    SaveIniSettingsToMemory();
15456
0
    ImGuiID root_id = 0; // Rebuild all
15457
0
    DockContextClearNodes(ctx, root_id, false);
15458
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15459
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15460
0
}
15461
15462
// Docking context update function, called by NewFrame()
15463
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15464
69.6k
{
15465
69.6k
    ImGuiContext& g = *ctx;
15466
69.6k
    ImGuiDockContext* dc = &ctx->DockContext;
15467
69.6k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15468
0
    {
15469
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15470
0
            DockContextClearNodes(ctx, 0, true);
15471
0
        return;
15472
0
    }
15473
15474
    // Setting NoSplit at runtime merges all nodes
15475
69.6k
    if (g.IO.ConfigDockingNoSplit)
15476
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15477
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15478
0
                if (node->IsRootNode() && node->IsSplitNode())
15479
0
                {
15480
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15481
                    //dc->WantFullRebuild = true;
15482
0
                }
15483
15484
    // Process full rebuild
15485
#if 0
15486
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15487
        dc->WantFullRebuild = true;
15488
#endif
15489
69.6k
    if (dc->WantFullRebuild)
15490
0
    {
15491
0
        DockContextRebuildNodes(ctx);
15492
0
        dc->WantFullRebuild = false;
15493
0
    }
15494
15495
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15496
69.6k
    for (ImGuiDockRequest& req : dc->Requests)
15497
0
    {
15498
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15499
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15500
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15501
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15502
0
    }
15503
69.6k
}
15504
15505
// Docking context update function, called by NewFrame()
15506
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15507
69.6k
{
15508
69.6k
    ImGuiContext& g = *ctx;
15509
69.6k
    ImGuiDockContext* dc = &ctx->DockContext;
15510
69.6k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15511
0
        return;
15512
15513
    // [DEBUG] Store hovered dock node.
15514
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15515
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15516
69.6k
    g.DebugHoveredDockNode = NULL;
15517
69.6k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15518
2.62k
    {
15519
2.62k
        if (hovered_window->DockNodeAsHost)
15520
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15521
2.62k
        else if (hovered_window->RootWindow->DockNode)
15522
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15523
2.62k
    }
15524
15525
    // Process Docking requests
15526
69.6k
    for (ImGuiDockRequest& req : dc->Requests)
15527
0
        if (req.Type == ImGuiDockRequestType_Dock)
15528
0
            DockContextProcessDock(ctx, &req);
15529
69.6k
    dc->Requests.resize(0);
15530
15531
    // Create windows for each automatic docking nodes
15532
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15533
69.6k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15534
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15535
0
            if (node->IsFloatingNode())
15536
0
                DockNodeUpdate(node);
15537
69.6k
}
15538
15539
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15540
69.6k
{
15541
    // Draw backgrounds of node missing their window
15542
69.6k
    ImGuiContext& g = *ctx;
15543
69.6k
    ImGuiDockContext* dc = &g.DockContext;
15544
69.6k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15545
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15546
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15547
0
            {
15548
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15549
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15550
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15551
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15552
0
            }
15553
69.6k
}
15554
15555
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15556
0
{
15557
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15558
0
}
15559
15560
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15561
0
{
15562
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15563
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15564
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15565
0
    ImGuiID id = 0x0001;
15566
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15567
0
        id++;
15568
0
    return id;
15569
0
}
15570
15571
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15572
0
{
15573
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15574
0
    ImGuiContext& g = *ctx;
15575
0
    if (id == 0)
15576
0
        id = DockContextGenNodeID(ctx);
15577
0
    else
15578
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15579
15580
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15581
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15582
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15583
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15584
0
    return node;
15585
0
}
15586
15587
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15588
0
{
15589
0
    ImGuiContext& g = *ctx;
15590
0
    ImGuiDockContext* dc = &ctx->DockContext;
15591
15592
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15593
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15594
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15595
0
    IM_ASSERT(node->Windows.Size == 0);
15596
15597
0
    if (node->HostWindow)
15598
0
        node->HostWindow->DockNodeAsHost = NULL;
15599
15600
0
    ImGuiDockNode* parent_node = node->ParentNode;
15601
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15602
0
    if (merge)
15603
0
    {
15604
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15605
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15606
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15607
0
    }
15608
0
    else
15609
0
    {
15610
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15611
0
            if (parent_node->ChildNodes[n] == node)
15612
0
                node->ParentNode->ChildNodes[n] = NULL;
15613
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15614
0
        IM_DELETE(node);
15615
0
    }
15616
0
}
15617
15618
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15619
0
{
15620
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15621
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15622
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15623
0
}
15624
15625
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15626
struct ImGuiDockContextPruneNodeData
15627
{
15628
    int         CountWindows, CountChildWindows, CountChildNodes;
15629
    ImGuiID     RootId;
15630
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15631
};
15632
15633
// Garbage collect unused nodes (run once at init time)
15634
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15635
0
{
15636
0
    ImGuiContext& g = *ctx;
15637
0
    ImGuiDockContext* dc = &ctx->DockContext;
15638
0
    IM_ASSERT(g.Windows.Size == 0);
15639
15640
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15641
0
    pool.Reserve(dc->NodesSettings.Size);
15642
15643
    // Count child nodes and compute RootID
15644
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15645
0
    {
15646
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15647
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15648
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15649
0
        if (settings->ParentNodeId)
15650
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15651
0
    }
15652
15653
    // Count reference to dock ids from dockspaces
15654
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15655
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15656
0
    {
15657
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15658
0
        if (settings->ParentWindowId != 0)
15659
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15660
0
                if (window_settings->DockId)
15661
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15662
0
                        data->CountChildNodes++;
15663
0
    }
15664
15665
    // Count reference to dock ids from window settings
15666
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15667
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15668
0
        if (ImGuiID dock_id = settings->DockId)
15669
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15670
0
            {
15671
0
                data->CountWindows++;
15672
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15673
0
                    data_root->CountChildWindows++;
15674
0
            }
15675
15676
    // Prune
15677
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15678
0
    {
15679
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15680
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15681
0
        if (data->CountWindows > 1)
15682
0
            continue;
15683
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15684
15685
0
        bool remove = false;
15686
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15687
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15688
0
        remove |= (data_root->CountChildWindows == 0);
15689
0
        if (remove)
15690
0
        {
15691
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15692
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15693
0
            settings->ID = 0;
15694
0
        }
15695
0
    }
15696
0
}
15697
15698
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15699
0
{
15700
    // Build nodes
15701
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15702
0
    {
15703
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15704
0
        if (settings->ID == 0)
15705
0
            continue;
15706
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15707
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15708
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15709
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15710
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15711
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15712
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15713
0
            node->ParentNode->ChildNodes[0] = node;
15714
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15715
0
            node->ParentNode->ChildNodes[1] = node;
15716
0
        node->SelectedTabId = settings->SelectedTabId;
15717
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15718
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15719
15720
        // Bind host window immediately if it already exist (in case of a rebuild)
15721
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15722
0
        char host_window_title[20];
15723
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15724
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15725
0
    }
15726
0
}
15727
15728
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15729
0
{
15730
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15731
0
    ImGuiContext& g = *ctx;
15732
0
    for (ImGuiWindow* window : g.Windows)
15733
0
    {
15734
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15735
0
            continue;
15736
0
        if (window->DockNode != NULL)
15737
0
            continue;
15738
15739
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15740
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15741
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15742
0
            DockNodeAddWindow(node, window, true);
15743
0
    }
15744
0
}
15745
15746
//-----------------------------------------------------------------------------
15747
// Docking: ImGuiDockContext Docking/Undocking functions
15748
//-----------------------------------------------------------------------------
15749
// - DockContextQueueDock()
15750
// - DockContextQueueUndockWindow()
15751
// - DockContextQueueUndockNode()
15752
// - DockContextQueueNotifyRemovedNode()
15753
// - DockContextProcessDock()
15754
// - DockContextProcessUndockWindow()
15755
// - DockContextProcessUndockNode()
15756
// - DockContextCalcDropPosForDocking()
15757
//-----------------------------------------------------------------------------
15758
15759
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15760
0
{
15761
0
    IM_ASSERT(target != payload);
15762
0
    ImGuiDockRequest req;
15763
0
    req.Type = ImGuiDockRequestType_Dock;
15764
0
    req.DockTargetWindow = target;
15765
0
    req.DockTargetNode = target_node;
15766
0
    req.DockPayload = payload;
15767
0
    req.DockSplitDir = split_dir;
15768
0
    req.DockSplitRatio = split_ratio;
15769
0
    req.DockSplitOuter = split_outer;
15770
0
    ctx->DockContext.Requests.push_back(req);
15771
0
}
15772
15773
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15774
0
{
15775
0
    ImGuiDockRequest req;
15776
0
    req.Type = ImGuiDockRequestType_Undock;
15777
0
    req.UndockTargetWindow = window;
15778
0
    ctx->DockContext.Requests.push_back(req);
15779
0
}
15780
15781
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15782
0
{
15783
0
    ImGuiDockRequest req;
15784
0
    req.Type = ImGuiDockRequestType_Undock;
15785
0
    req.UndockTargetNode = node;
15786
0
    ctx->DockContext.Requests.push_back(req);
15787
0
}
15788
15789
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15790
0
{
15791
0
    ImGuiDockContext* dc = &ctx->DockContext;
15792
0
    for (ImGuiDockRequest& req : dc->Requests)
15793
0
        if (req.DockTargetNode == node)
15794
0
            req.Type = ImGuiDockRequestType_None;
15795
0
}
15796
15797
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15798
0
{
15799
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15800
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15801
15802
0
    ImGuiContext& g = *ctx;
15803
0
    IM_UNUSED(g);
15804
15805
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15806
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15807
0
    ImGuiDockNode* node = req->DockTargetNode;
15808
0
    if (payload_window)
15809
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15810
0
    else
15811
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15812
15813
    // Decide which Tab will be selected at the end of the operation
15814
0
    ImGuiID next_selected_id = 0;
15815
0
    ImGuiDockNode* payload_node = NULL;
15816
0
    if (payload_window)
15817
0
    {
15818
0
        payload_node = payload_window->DockNodeAsHost;
15819
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15820
0
        if (payload_node && payload_node->IsLeafNode())
15821
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15822
0
        if (payload_node == NULL)
15823
0
            next_selected_id = payload_window->TabId;
15824
0
    }
15825
15826
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15827
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15828
0
    if (node)
15829
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15830
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15831
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15832
15833
    // Create new node and add existing window to it
15834
0
    if (node == NULL)
15835
0
    {
15836
0
        node = DockContextAddNode(ctx, 0);
15837
0
        node->Pos = target_window->Pos;
15838
0
        node->Size = target_window->Size;
15839
0
        if (target_window->DockNodeAsHost == NULL)
15840
0
        {
15841
0
            DockNodeAddWindow(node, target_window, true);
15842
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15843
0
            target_window->DockIsActive = true;
15844
0
        }
15845
0
    }
15846
15847
0
    ImGuiDir split_dir = req->DockSplitDir;
15848
0
    if (split_dir != ImGuiDir_None)
15849
0
    {
15850
        // Split into two, one side will be our payload node unless we are dropping a loose window
15851
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15852
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15853
0
        const float split_ratio = req->DockSplitRatio;
15854
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15855
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15856
0
        new_node->HostWindow = node->HostWindow;
15857
0
        node = new_node;
15858
0
    }
15859
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15860
15861
0
    if (node != payload_node)
15862
0
    {
15863
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15864
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15865
0
        {
15866
0
            DockNodeAddTabBar(node);
15867
0
            for (int n = 0; n < node->Windows.Size; n++)
15868
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15869
0
        }
15870
15871
0
        if (payload_node != NULL)
15872
0
        {
15873
            // Transfer full payload node (with 1+ child windows or child nodes)
15874
0
            if (payload_node->IsSplitNode())
15875
0
            {
15876
0
                if (node->Windows.Size > 0)
15877
0
                {
15878
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15879
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15880
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15881
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15882
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15883
0
                    if (visible_node->TabBar)
15884
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15885
0
                    DockNodeMoveWindows(node, visible_node);
15886
0
                    DockNodeMoveWindows(visible_node, node);
15887
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15888
0
                }
15889
0
                if (node->IsCentralNode())
15890
0
                {
15891
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15892
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15893
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15894
0
                    IM_ASSERT(last_focused_node != NULL);
15895
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15896
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15897
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15898
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15899
0
                    last_focused_root_node->CentralNode = last_focused_node;
15900
0
                }
15901
15902
0
                IM_ASSERT(node->Windows.Size == 0);
15903
0
                DockNodeMoveChildNodes(node, payload_node);
15904
0
            }
15905
0
            else
15906
0
            {
15907
0
                const ImGuiID payload_dock_id = payload_node->ID;
15908
0
                DockNodeMoveWindows(node, payload_node);
15909
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15910
0
            }
15911
0
            DockContextRemoveNode(ctx, payload_node, true);
15912
0
        }
15913
0
        else if (payload_window)
15914
0
        {
15915
            // Transfer single window
15916
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15917
0
            node->VisibleWindow = payload_window;
15918
0
            DockNodeAddWindow(node, payload_window, true);
15919
0
            if (payload_dock_id != 0)
15920
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15921
0
        }
15922
0
    }
15923
0
    else
15924
0
    {
15925
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15926
0
        node->WantHiddenTabBarUpdate = true;
15927
0
    }
15928
15929
    // Update selection immediately
15930
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15931
0
        tab_bar->NextSelectedTabId = next_selected_id;
15932
0
    MarkIniSettingsDirty();
15933
0
}
15934
15935
// Problem:
15936
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15937
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15938
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15939
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15940
// Solution:
15941
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15942
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15943
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15944
0
{
15945
0
    if (ref_viewport == NULL)
15946
0
        return size;
15947
15948
0
    ImGuiContext& g = *GImGui;
15949
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
15950
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15951
0
    {
15952
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15953
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
15954
0
    }
15955
0
    return ImMin(size, max_size);
15956
0
}
15957
15958
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15959
0
{
15960
0
    ImGuiContext& g = *ctx;
15961
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15962
0
    if (window->DockNode)
15963
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15964
0
    else
15965
0
        window->DockId = 0;
15966
0
    window->Collapsed = false;
15967
0
    window->DockIsActive = false;
15968
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15969
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15970
15971
0
    MarkIniSettingsDirty();
15972
0
}
15973
15974
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15975
0
{
15976
0
    ImGuiContext& g = *ctx;
15977
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15978
0
    IM_ASSERT(node->IsLeafNode());
15979
0
    IM_ASSERT(node->Windows.Size >= 1);
15980
15981
0
    if (node->IsRootNode() || node->IsCentralNode())
15982
0
    {
15983
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15984
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15985
0
        new_node->Pos = node->Pos;
15986
0
        new_node->Size = node->Size;
15987
0
        new_node->SizeRef = node->SizeRef;
15988
0
        DockNodeMoveWindows(new_node, node);
15989
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15990
0
        node = new_node;
15991
0
    }
15992
0
    else
15993
0
    {
15994
        // Otherwise extract our node and merge our sibling back into the parent node.
15995
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15996
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15997
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15998
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15999
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16000
0
        node->ParentNode = NULL;
16001
0
    }
16002
0
    for (ImGuiWindow* window : node->Windows)
16003
0
    {
16004
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16005
0
        if (window->ParentWindow)
16006
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16007
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16008
0
    }
16009
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16010
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16011
0
    node->WantMouseMove = true;
16012
0
    MarkIniSettingsDirty();
16013
0
}
16014
16015
// This is mostly used for automation.
16016
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16017
0
{
16018
0
    if (target != NULL && target_node == NULL)
16019
0
        target_node = target->DockNode;
16020
16021
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16022
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16023
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16024
0
        split_outer = true;
16025
0
    ImGuiDockPreviewData split_data;
16026
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16027
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16028
0
        return false;
16029
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16030
0
    return true;
16031
0
}
16032
16033
//-----------------------------------------------------------------------------
16034
// Docking: ImGuiDockNode
16035
//-----------------------------------------------------------------------------
16036
// - DockNodeGetTabOrder()
16037
// - DockNodeAddWindow()
16038
// - DockNodeRemoveWindow()
16039
// - DockNodeMoveChildNodes()
16040
// - DockNodeMoveWindows()
16041
// - DockNodeApplyPosSizeToWindows()
16042
// - DockNodeHideHostWindow()
16043
// - ImGuiDockNodeFindInfoResults
16044
// - DockNodeFindInfo()
16045
// - DockNodeFindWindowByID()
16046
// - DockNodeUpdateFlagsAndCollapse()
16047
// - DockNodeUpdateHasCentralNodeFlag()
16048
// - DockNodeUpdateVisibleFlag()
16049
// - DockNodeStartMouseMovingWindow()
16050
// - DockNodeUpdate()
16051
// - DockNodeUpdateWindowMenu()
16052
// - DockNodeBeginAmendTabBar()
16053
// - DockNodeEndAmendTabBar()
16054
// - DockNodeUpdateTabBar()
16055
// - DockNodeAddTabBar()
16056
// - DockNodeRemoveTabBar()
16057
// - DockNodeIsDropAllowedOne()
16058
// - DockNodeIsDropAllowed()
16059
// - DockNodeCalcTabBarLayout()
16060
// - DockNodeCalcSplitRects()
16061
// - DockNodeCalcDropRectsAndTestMousePos()
16062
// - DockNodePreviewDockSetup()
16063
// - DockNodePreviewDockRender()
16064
//-----------------------------------------------------------------------------
16065
16066
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16067
0
{
16068
0
    ID = id;
16069
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16070
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16071
0
    TabBar = NULL;
16072
0
    SplitAxis = ImGuiAxis_None;
16073
16074
0
    State = ImGuiDockNodeState_Unknown;
16075
0
    LastBgColor = IM_COL32_WHITE;
16076
0
    HostWindow = VisibleWindow = NULL;
16077
0
    CentralNode = OnlyNodeWithWindows = NULL;
16078
0
    CountNodeWithWindows = 0;
16079
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16080
0
    LastFocusedNodeId = 0;
16081
0
    SelectedTabId = 0;
16082
0
    WantCloseTabId = 0;
16083
0
    RefViewportId = 0;
16084
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16085
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16086
0
    IsVisible = true;
16087
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16088
0
    IsBgDrawnThisFrame = false;
16089
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16090
0
}
16091
16092
ImGuiDockNode::~ImGuiDockNode()
16093
0
{
16094
0
    IM_DELETE(TabBar);
16095
0
    TabBar = NULL;
16096
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16097
0
}
16098
16099
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16100
0
{
16101
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16102
0
    if (tab_bar == NULL)
16103
0
        return -1;
16104
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16105
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16106
0
}
16107
16108
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16109
0
{
16110
0
    window->Hidden = true;
16111
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16112
0
}
16113
16114
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16115
0
{
16116
0
    ImGuiContext& g = *GImGui; (void)g;
16117
0
    if (window->DockNode)
16118
0
    {
16119
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16120
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16121
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16122
0
    }
16123
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16124
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16125
16126
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16127
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16128
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16129
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16130
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16131
16132
0
    node->Windows.push_back(window);
16133
0
    node->WantHiddenTabBarUpdate = true;
16134
0
    window->DockNode = node;
16135
0
    window->DockId = node->ID;
16136
0
    window->DockIsActive = (node->Windows.Size > 1);
16137
0
    window->DockTabWantClose = false;
16138
16139
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16140
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16141
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16142
0
    {
16143
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16144
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16145
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16146
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16147
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16148
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16149
0
    }
16150
16151
    // Add to tab bar if requested
16152
0
    if (add_to_tab_bar)
16153
0
    {
16154
0
        if (node->TabBar == NULL)
16155
0
        {
16156
0
            DockNodeAddTabBar(node);
16157
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16158
16159
            // Add existing windows
16160
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16161
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16162
0
        }
16163
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16164
0
    }
16165
16166
0
    DockNodeUpdateVisibleFlag(node);
16167
16168
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16169
0
    if (node->HostWindow)
16170
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16171
0
}
16172
16173
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16174
0
{
16175
0
    ImGuiContext& g = *GImGui;
16176
0
    IM_ASSERT(window->DockNode == node);
16177
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16178
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16179
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16180
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16181
16182
0
    window->DockNode = NULL;
16183
0
    window->DockIsActive = window->DockTabWantClose = false;
16184
0
    window->DockId = save_dock_id;
16185
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16186
0
    if (window->ParentWindow)
16187
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16188
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16189
16190
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16191
0
    {
16192
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16193
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16194
0
        window->Viewport = NULL;
16195
0
        window->ViewportId = 0;
16196
0
        window->ViewportOwned = false;
16197
0
        window->Hidden = true;
16198
0
    }
16199
16200
    // Remove window
16201
0
    bool erased = false;
16202
0
    for (int n = 0; n < node->Windows.Size; n++)
16203
0
        if (node->Windows[n] == window)
16204
0
        {
16205
0
            node->Windows.erase(node->Windows.Data + n);
16206
0
            erased = true;
16207
0
            break;
16208
0
        }
16209
0
    if (!erased)
16210
0
        IM_ASSERT(erased);
16211
0
    if (node->VisibleWindow == window)
16212
0
        node->VisibleWindow = NULL;
16213
16214
    // Remove tab and possibly tab bar
16215
0
    node->WantHiddenTabBarUpdate = true;
16216
0
    if (node->TabBar)
16217
0
    {
16218
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16219
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16220
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16221
0
            DockNodeRemoveTabBar(node);
16222
0
    }
16223
16224
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16225
0
    {
16226
        // Automatic dock node delete themselves if they are not holding at least one tab
16227
0
        DockContextRemoveNode(&g, node, true);
16228
0
        return;
16229
0
    }
16230
16231
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16232
0
    {
16233
0
        ImGuiWindow* remaining_window = node->Windows[0];
16234
        // Note: we used to transport viewport ownership here.
16235
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16236
0
    }
16237
16238
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16239
0
    DockNodeUpdateVisibleFlag(node);
16240
0
}
16241
16242
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16243
0
{
16244
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16245
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16246
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16247
0
    if (dst_node->ChildNodes[0])
16248
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16249
0
    if (dst_node->ChildNodes[1])
16250
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16251
0
    dst_node->SplitAxis = src_node->SplitAxis;
16252
0
    dst_node->SizeRef = src_node->SizeRef;
16253
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16254
0
}
16255
16256
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16257
0
{
16258
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16259
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16260
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16261
0
    if (src_tab_bar != NULL)
16262
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16263
16264
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16265
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16266
0
    if (move_tab_bar)
16267
0
    {
16268
0
        dst_node->TabBar = src_node->TabBar;
16269
0
        src_node->TabBar = NULL;
16270
0
    }
16271
16272
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16273
0
    for (ImGuiWindow* window : src_node->Windows)
16274
0
    {
16275
0
        window->DockNode = NULL;
16276
0
        window->DockIsActive = false;
16277
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16278
0
    }
16279
0
    src_node->Windows.clear();
16280
16281
0
    if (!move_tab_bar && src_node->TabBar)
16282
0
    {
16283
0
        if (dst_node->TabBar)
16284
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16285
0
        DockNodeRemoveTabBar(src_node);
16286
0
    }
16287
0
}
16288
16289
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16290
0
{
16291
0
    for (ImGuiWindow* window : node->Windows)
16292
0
    {
16293
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16294
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16295
0
    }
16296
0
}
16297
16298
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16299
0
{
16300
0
    if (node->HostWindow)
16301
0
    {
16302
0
        if (node->HostWindow->DockNodeAsHost == node)
16303
0
            node->HostWindow->DockNodeAsHost = NULL;
16304
0
        node->HostWindow = NULL;
16305
0
    }
16306
16307
0
    if (node->Windows.Size == 1)
16308
0
    {
16309
0
        node->VisibleWindow = node->Windows[0];
16310
0
        node->Windows[0]->DockIsActive = false;
16311
0
    }
16312
16313
0
    if (node->TabBar)
16314
0
        DockNodeRemoveTabBar(node);
16315
0
}
16316
16317
// Search function called once by root node in DockNodeUpdate()
16318
struct ImGuiDockNodeTreeInfo
16319
{
16320
    ImGuiDockNode*      CentralNode;
16321
    ImGuiDockNode*      FirstNodeWithWindows;
16322
    int                 CountNodesWithWindows;
16323
    //ImGuiWindowClass  WindowClassForMerges;
16324
16325
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16326
};
16327
16328
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16329
0
{
16330
0
    if (node->Windows.Size > 0)
16331
0
    {
16332
0
        if (info->FirstNodeWithWindows == NULL)
16333
0
            info->FirstNodeWithWindows = node;
16334
0
        info->CountNodesWithWindows++;
16335
0
    }
16336
0
    if (node->IsCentralNode())
16337
0
    {
16338
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16339
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16340
0
        info->CentralNode = node;
16341
0
    }
16342
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16343
0
        return;
16344
0
    if (node->ChildNodes[0])
16345
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16346
0
    if (node->ChildNodes[1])
16347
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16348
0
}
16349
16350
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16351
0
{
16352
0
    IM_ASSERT(id != 0);
16353
0
    for (ImGuiWindow* window : node->Windows)
16354
0
        if (window->ID == id)
16355
0
            return window;
16356
0
    return NULL;
16357
0
}
16358
16359
// - Remove inactive windows/nodes.
16360
// - Update visibility flag.
16361
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16362
0
{
16363
0
    ImGuiContext& g = *GImGui;
16364
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16365
16366
    // Inherit most flags
16367
0
    if (node->ParentNode)
16368
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16369
16370
    // Recurse into children
16371
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16372
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16373
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16374
0
    node->HasCentralNodeChild = false;
16375
0
    if (node->ChildNodes[0])
16376
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16377
0
    if (node->ChildNodes[1])
16378
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16379
16380
    // Remove inactive windows, collapse nodes
16381
    // Merge node flags overrides stored in windows
16382
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16383
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16384
0
    {
16385
0
        ImGuiWindow* window = node->Windows[window_n];
16386
0
        IM_ASSERT(window->DockNode == node);
16387
16388
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16389
0
        bool remove = false;
16390
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16391
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16392
0
        remove |= (window->DockTabWantClose);
16393
0
        if (remove)
16394
0
        {
16395
0
            window->DockTabWantClose = false;
16396
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16397
0
            {
16398
0
                DockNodeHideHostWindow(node);
16399
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16400
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16401
0
                return;
16402
0
            }
16403
0
            DockNodeRemoveWindow(node, window, node->ID);
16404
0
            window_n--;
16405
0
            continue;
16406
0
        }
16407
16408
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16409
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16410
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16411
0
    }
16412
0
    node->UpdateMergedFlags();
16413
16414
    // Auto-hide tab bar option
16415
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16416
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16417
0
        node->WantHiddenTabBarToggle = true;
16418
0
    node->WantHiddenTabBarUpdate = false;
16419
16420
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16421
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16422
0
        node->WantHiddenTabBarToggle = false;
16423
16424
    // Apply toggles at a single point of the frame (here!)
16425
0
    if (node->Windows.Size > 1)
16426
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16427
0
    else if (node->WantHiddenTabBarToggle)
16428
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16429
0
    node->WantHiddenTabBarToggle = false;
16430
16431
0
    DockNodeUpdateVisibleFlag(node);
16432
0
}
16433
16434
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16435
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16436
0
{
16437
0
    node->HasCentralNodeChild = false;
16438
0
    if (node->ChildNodes[0])
16439
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16440
0
    if (node->ChildNodes[1])
16441
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16442
0
    if (node->IsRootNode())
16443
0
    {
16444
0
        ImGuiDockNode* mark_node = node->CentralNode;
16445
0
        while (mark_node)
16446
0
        {
16447
0
            mark_node->HasCentralNodeChild = true;
16448
0
            mark_node = mark_node->ParentNode;
16449
0
        }
16450
0
    }
16451
0
}
16452
16453
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16454
0
{
16455
    // Update visibility flag
16456
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16457
0
    is_visible |= (node->Windows.Size > 0);
16458
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16459
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16460
0
    node->IsVisible = is_visible;
16461
0
}
16462
16463
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16464
0
{
16465
0
    ImGuiContext& g = *GImGui;
16466
0
    IM_ASSERT(node->WantMouseMove == true);
16467
0
    StartMouseMovingWindow(window);
16468
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16469
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16470
0
    node->WantMouseMove = false;
16471
0
}
16472
16473
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16474
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16475
0
{
16476
0
    DockNodeUpdateFlagsAndCollapse(node);
16477
16478
    // - Setup central node pointers
16479
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16480
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16481
0
    ImGuiDockNodeTreeInfo info;
16482
0
    DockNodeFindInfo(node, &info);
16483
0
    node->CentralNode = info.CentralNode;
16484
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16485
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16486
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16487
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16488
16489
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16490
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16491
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16492
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16493
0
    {
16494
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16495
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16496
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16497
0
            {
16498
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16499
0
                break;
16500
0
            }
16501
0
    }
16502
16503
0
    ImGuiDockNode* mark_node = node->CentralNode;
16504
0
    while (mark_node)
16505
0
    {
16506
0
        mark_node->HasCentralNodeChild = true;
16507
0
        mark_node = mark_node->ParentNode;
16508
0
    }
16509
0
}
16510
16511
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16512
0
{
16513
    // Remove ourselves from any previous different host window
16514
    // This can happen if a user mistakenly does (see #4295 for details):
16515
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16516
    //  - N+1: NewFrame()                   // will create floating host window for that node
16517
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16518
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16519
0
        node->HostWindow->DockNodeAsHost = NULL;
16520
16521
0
    host_window->DockNodeAsHost = node;
16522
0
    node->HostWindow = host_window;
16523
0
}
16524
16525
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16526
0
{
16527
0
    ImGuiContext& g = *GImGui;
16528
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16529
0
    node->LastFrameAlive = g.FrameCount;
16530
0
    node->IsBgDrawnThisFrame = false;
16531
16532
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16533
0
    if (node->IsRootNode())
16534
0
        DockNodeUpdateForRootNode(node);
16535
16536
    // Remove tab bar if not needed
16537
0
    if (node->TabBar && node->IsNoTabBar())
16538
0
        DockNodeRemoveTabBar(node);
16539
16540
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16541
0
    bool want_to_hide_host_window = false;
16542
0
    if (node->IsFloatingNode())
16543
0
    {
16544
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16545
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16546
0
                want_to_hide_host_window = true;
16547
0
        if (node->CountNodeWithWindows == 0)
16548
0
            want_to_hide_host_window = true;
16549
0
    }
16550
0
    if (want_to_hide_host_window)
16551
0
    {
16552
0
        if (node->Windows.Size == 1)
16553
0
        {
16554
            // Floating window pos/size is authoritative
16555
0
            ImGuiWindow* single_window = node->Windows[0];
16556
0
            node->Pos = single_window->Pos;
16557
0
            node->Size = single_window->SizeFull;
16558
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16559
16560
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16561
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16562
0
                FocusWindow(single_window);
16563
0
            if (node->HostWindow)
16564
0
            {
16565
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16566
0
                single_window->Viewport = node->HostWindow->Viewport;
16567
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16568
0
                if (node->HostWindow->ViewportOwned)
16569
0
                {
16570
0
                    single_window->Viewport->ID = single_window->ID;
16571
0
                    single_window->Viewport->Window = single_window;
16572
0
                    single_window->ViewportOwned = true;
16573
0
                }
16574
0
            }
16575
0
            node->RefViewportId = single_window->ViewportId;
16576
0
        }
16577
16578
0
        DockNodeHideHostWindow(node);
16579
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16580
0
        node->WantCloseAll = false;
16581
0
        node->WantCloseTabId = 0;
16582
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16583
0
        node->LastFrameActive = g.FrameCount;
16584
16585
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16586
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16587
0
        return;
16588
0
    }
16589
16590
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16591
    // while the expected visible window is resizing itself.
16592
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16593
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16594
    //   N+0: Begin(): window created (with no known size), node is created
16595
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16596
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16597
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16598
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16599
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16600
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16601
0
    {
16602
0
        IM_ASSERT(node->Windows.Size > 0);
16603
0
        ImGuiWindow* ref_window = NULL;
16604
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16605
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16606
0
        if (ref_window == NULL)
16607
0
            ref_window = node->Windows[0];
16608
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16609
0
        {
16610
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16611
0
            return;
16612
0
        }
16613
0
    }
16614
16615
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16616
16617
    // Decide if the node will have a close button and a window menu button
16618
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16619
0
    node->HasCloseButton = false;
16620
0
    for (ImGuiWindow* window : node->Windows)
16621
0
    {
16622
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16623
0
        node->HasCloseButton |= window->HasCloseButton;
16624
0
        window->DockIsActive = (node->Windows.Size > 1);
16625
0
    }
16626
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16627
0
        node->HasCloseButton = false;
16628
16629
    // Bind or create host window
16630
0
    ImGuiWindow* host_window = NULL;
16631
0
    bool beginned_into_host_window = false;
16632
0
    if (node->IsDockSpace())
16633
0
    {
16634
        // [Explicit root dockspace node]
16635
0
        IM_ASSERT(node->HostWindow);
16636
0
        host_window = node->HostWindow;
16637
0
    }
16638
0
    else
16639
0
    {
16640
        // [Automatic root or child nodes]
16641
0
        if (node->IsRootNode() && node->IsVisible)
16642
0
        {
16643
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16644
16645
            // Sync Pos
16646
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16647
0
                SetNextWindowPos(ref_window->Pos);
16648
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16649
0
                SetNextWindowPos(node->Pos);
16650
16651
            // Sync Size
16652
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16653
0
                SetNextWindowSize(ref_window->SizeFull);
16654
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16655
0
                SetNextWindowSize(node->Size);
16656
16657
            // Sync Collapsed
16658
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16659
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16660
16661
            // Sync Viewport
16662
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16663
0
                SetNextWindowViewport(ref_window->ViewportId);
16664
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16665
0
                SetNextWindowViewport(node->RefViewportId);
16666
16667
0
            SetNextWindowClass(&node->WindowClass);
16668
16669
            // Begin into the host window
16670
0
            char window_label[20];
16671
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16672
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16673
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16674
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16675
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16676
16677
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16678
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16679
0
            Begin(window_label, NULL, window_flags);
16680
0
            PopStyleVar();
16681
0
            beginned_into_host_window = true;
16682
16683
0
            host_window = g.CurrentWindow;
16684
0
            DockNodeSetupHostWindow(node, host_window);
16685
0
            host_window->DC.CursorPos = host_window->Pos;
16686
0
            node->Pos = host_window->Pos;
16687
0
            node->Size = host_window->Size;
16688
16689
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16690
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16691
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16692
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16693
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16694
            // after the dock host window, losing their top-most status.
16695
0
            if (node->HostWindow->Appearing)
16696
0
                BringWindowToDisplayFront(node->HostWindow);
16697
16698
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16699
0
        }
16700
0
        else if (node->ParentNode)
16701
0
        {
16702
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16703
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16704
0
        }
16705
0
        if (node->WantMouseMove && node->HostWindow)
16706
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16707
0
    }
16708
0
    node->RefViewportId = 0; // Clear when we have a host window
16709
16710
    // Update focused node (the one whose title bar is highlight) within a node tree
16711
0
    if (node->IsSplitNode())
16712
0
        IM_ASSERT(node->TabBar == NULL);
16713
0
    if (node->IsRootNode())
16714
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16715
0
            while (p_window != NULL && p_window->DockNode != NULL)
16716
0
            {
16717
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16718
0
                if (p_node == node)
16719
0
                {
16720
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16721
0
                    break;
16722
0
                }
16723
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16724
0
            }
16725
16726
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16727
0
    ImGuiDockNode* central_node = node->CentralNode;
16728
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16729
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16730
0
    if (central_node_hole)
16731
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16732
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16733
0
                central_node_hole_register_hit_test_hole = false;
16734
0
    if (central_node_hole_register_hit_test_hole)
16735
0
    {
16736
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16737
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16738
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16739
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16740
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16741
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16742
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16743
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16744
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16745
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16746
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16747
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16748
0
        if (central_node_hole && !hole_rect.IsInverted())
16749
0
        {
16750
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16751
0
            if (host_window->ParentWindow)
16752
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16753
0
        }
16754
0
    }
16755
16756
    // Update position/size, process and draw resizing splitters
16757
0
    if (node->IsRootNode() && host_window)
16758
0
    {
16759
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16760
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
16761
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
16762
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
16763
0
        DockNodeTreeUpdateSplitter(node);
16764
0
        PopStyleColor(3);
16765
0
    }
16766
16767
    // Draw empty node background (currently can only be the Central Node)
16768
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16769
0
    {
16770
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16771
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16772
0
        if (node->LastBgColor != 0)
16773
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16774
0
        node->IsBgDrawnThisFrame = true;
16775
0
    }
16776
16777
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16778
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16779
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16780
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16781
0
    if (render_dockspace_bg && node->IsVisible)
16782
0
    {
16783
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16784
0
        if (central_node_hole)
16785
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16786
0
        else
16787
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16788
0
    }
16789
16790
    // Draw and populate Tab Bar
16791
0
    if (host_window)
16792
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16793
0
    if (host_window && node->Windows.Size > 0)
16794
0
    {
16795
0
        DockNodeUpdateTabBar(node, host_window);
16796
0
    }
16797
0
    else
16798
0
    {
16799
0
        node->WantCloseAll = false;
16800
0
        node->WantCloseTabId = 0;
16801
0
        node->IsFocused = false;
16802
0
    }
16803
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16804
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16805
0
    else if (node->Windows.Size > 0)
16806
0
        node->SelectedTabId = node->Windows[0]->TabId;
16807
16808
    // Draw payload drop target
16809
0
    if (host_window && node->IsVisible)
16810
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16811
0
            BeginDockableDragDropTarget(host_window);
16812
16813
    // We update this after DockNodeUpdateTabBar()
16814
0
    node->LastFrameActive = g.FrameCount;
16815
16816
    // Recurse into children
16817
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16818
0
    if (host_window)
16819
0
    {
16820
0
        if (node->ChildNodes[0])
16821
0
            DockNodeUpdate(node->ChildNodes[0]);
16822
0
        if (node->ChildNodes[1])
16823
0
            DockNodeUpdate(node->ChildNodes[1]);
16824
16825
        // Render outer borders last (after the tab bar)
16826
0
        if (node->IsRootNode())
16827
0
            RenderWindowOuterBorders(host_window);
16828
0
    }
16829
16830
    // End host window
16831
0
    if (beginned_into_host_window) //-V1020
16832
0
        End();
16833
0
}
16834
16835
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16836
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16837
0
{
16838
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16839
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16840
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16841
0
        return d;
16842
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16843
0
}
16844
16845
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16846
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16847
// Custom overrides may want to decorate, group, sort entries.
16848
// Please note those are internal structures: if you copy this expect occasional breakage.
16849
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
16850
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16851
0
{
16852
0
    IM_UNUSED(ctx);
16853
0
    if (tab_bar->Tabs.Size == 1)
16854
0
    {
16855
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16856
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16857
0
            node->WantHiddenTabBarToggle = true;
16858
0
    }
16859
0
    else
16860
0
    {
16861
        // Display a selectable list of windows in this docking node
16862
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16863
0
        {
16864
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16865
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16866
0
                continue;
16867
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16868
0
                TabBarQueueFocus(tab_bar, tab);
16869
0
            SameLine();
16870
0
            Text("   ");
16871
0
        }
16872
0
    }
16873
0
}
16874
16875
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16876
0
{
16877
    // Try to position the menu so it is more likely to stays within the same viewport
16878
0
    ImGuiContext& g = *GImGui;
16879
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16880
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16881
0
    else
16882
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16883
0
    if (BeginPopup("#WindowMenu"))
16884
0
    {
16885
0
        node->IsFocused = true;
16886
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16887
0
        EndPopup();
16888
0
    }
16889
0
}
16890
16891
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16892
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16893
0
{
16894
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16895
0
        return false;
16896
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16897
0
        return false;
16898
0
    if (node->TabBar->ID == 0)
16899
0
        return false;
16900
0
    Begin(node->HostWindow->Name);
16901
0
    PushOverrideID(node->ID);
16902
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
16903
0
    IM_UNUSED(ret);
16904
0
    IM_ASSERT(ret);
16905
0
    return true;
16906
0
}
16907
16908
void ImGui::DockNodeEndAmendTabBar()
16909
0
{
16910
0
    EndTabBar();
16911
0
    PopID();
16912
0
    End();
16913
0
}
16914
16915
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16916
0
{
16917
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16918
0
    ImGuiContext& g = *GImGui;
16919
0
    if (g.NavWindowingTarget)
16920
0
        return (g.NavWindowingTarget->DockNode == node);
16921
16922
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16923
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16924
0
    {
16925
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16926
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16927
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16928
0
            parent_window = parent_window->ParentWindow->RootWindow;
16929
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16930
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16931
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16932
0
                return true;
16933
0
    }
16934
0
    return false;
16935
0
}
16936
16937
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16938
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16939
0
{
16940
0
    ImGuiContext& g = *GImGui;
16941
0
    ImGuiStyle& style = g.Style;
16942
16943
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16944
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16945
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16946
0
    node->WantCloseAll = false;
16947
0
    node->WantCloseTabId = 0;
16948
16949
    // Decide if we should use a focused title bar color
16950
0
    bool is_focused = false;
16951
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16952
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16953
0
        is_focused = true;
16954
16955
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16956
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16957
0
    {
16958
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16959
0
        node->IsFocused = is_focused;
16960
0
        if (is_focused)
16961
0
            node->LastFrameFocused = g.FrameCount;
16962
0
        if (node->VisibleWindow)
16963
0
        {
16964
            // Notify root of visible window (used to display title in OS task bar)
16965
0
            if (is_focused || root_node->VisibleWindow == NULL)
16966
0
                root_node->VisibleWindow = node->VisibleWindow;
16967
0
            if (node->TabBar)
16968
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16969
0
        }
16970
0
        return;
16971
0
    }
16972
16973
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16974
0
    bool backup_skip_item = host_window->SkipItems;
16975
0
    if (!node->IsDockSpace())
16976
0
    {
16977
0
        host_window->SkipItems = false;
16978
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16979
0
    }
16980
16981
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16982
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16983
    // as docked windows themselves will override the stack with their own root ID.
16984
0
    PushOverrideID(node->ID);
16985
0
    ImGuiTabBar* tab_bar = node->TabBar;
16986
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16987
0
    if (tab_bar == NULL)
16988
0
    {
16989
0
        DockNodeAddTabBar(node);
16990
0
        tab_bar = node->TabBar;
16991
0
    }
16992
16993
0
    ImGuiID focus_tab_id = 0;
16994
0
    node->IsFocused = is_focused;
16995
16996
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16997
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16998
16999
    // In a dock node, the Collapse Button turns into the Window Menu button.
17000
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17001
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17002
0
    {
17003
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17004
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17005
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17006
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17007
0
        is_focused |= node->IsFocused;
17008
0
    }
17009
17010
    // Layout
17011
0
    ImRect title_bar_rect, tab_bar_rect;
17012
0
    ImVec2 window_menu_button_pos;
17013
0
    ImVec2 close_button_pos;
17014
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17015
17016
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17017
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17018
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17019
0
    {
17020
0
        ImGuiWindow* window = node->Windows[window_n];
17021
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17022
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17023
0
    }
17024
17025
    // Title bar
17026
0
    if (is_focused)
17027
0
        node->LastFrameFocused = g.FrameCount;
17028
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17029
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17030
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17031
17032
    // Docking/Collapse button
17033
0
    if (has_window_menu_button)
17034
0
    {
17035
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17036
0
            OpenPopup("#WindowMenu");
17037
0
        if (IsItemActive())
17038
0
            focus_tab_id = tab_bar->SelectedTabId;
17039
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17040
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17041
0
    }
17042
17043
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17044
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17045
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17046
0
    {
17047
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17048
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17049
0
        tabs_unsorted_start = tab_n;
17050
0
    }
17051
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17052
0
    {
17053
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17054
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17055
0
        {
17056
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17057
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17058
0
        }
17059
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17060
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17061
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17062
0
    }
17063
17064
    // Apply NavWindow focus back to the tab bar
17065
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17066
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17067
17068
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17069
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17070
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17071
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17072
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17073
17074
    // Begin tab bar
17075
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17076
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17077
0
    if (!host_window->Collapsed && is_focused)
17078
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17079
0
    tab_bar->ID = GetID("#TabBar");
17080
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17081
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17082
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17083
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17084
17085
    // Backup style colors
17086
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17087
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17088
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17089
17090
    // Submit actual tabs
17091
0
    node->VisibleWindow = NULL;
17092
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17093
0
    {
17094
0
        ImGuiWindow* window = node->Windows[window_n];
17095
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17096
0
            continue;
17097
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17098
0
        {
17099
0
            ImGuiTabItemFlags tab_item_flags = 0;
17100
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17101
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17102
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17103
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17104
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17105
17106
            // Apply stored style overrides for the window
17107
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17108
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17109
17110
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17111
0
            bool tab_open = true;
17112
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17113
0
            if (!tab_open)
17114
0
                node->WantCloseTabId = window->TabId;
17115
0
            if (tab_bar->VisibleTabId == window->TabId)
17116
0
                node->VisibleWindow = window;
17117
17118
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17119
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17120
0
            window->DockTabItemRect = g.LastItemData.Rect;
17121
17122
            // Update navigation ID on menu layer
17123
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17124
0
                host_window->NavLastIds[1] = window->TabId;
17125
0
        }
17126
0
    }
17127
17128
    // Restore style colors
17129
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17130
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17131
17132
    // Notify root of visible window (used to display title in OS task bar)
17133
0
    if (node->VisibleWindow)
17134
0
        if (is_focused || root_node->VisibleWindow == NULL)
17135
0
            root_node->VisibleWindow = node->VisibleWindow;
17136
17137
    // Close button (after VisibleWindow was updated)
17138
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17139
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17140
0
    const bool close_button_is_visible = node->HasCloseButton;
17141
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17142
0
    if (close_button_is_visible)
17143
0
    {
17144
0
        if (!close_button_is_enabled)
17145
0
        {
17146
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17147
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17148
0
        }
17149
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17150
0
        {
17151
0
            node->WantCloseAll = true;
17152
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17153
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17154
0
        }
17155
        //if (IsItemActive())
17156
        //    focus_tab_id = tab_bar->SelectedTabId;
17157
0
        if (!close_button_is_enabled)
17158
0
        {
17159
0
            PopStyleColor();
17160
0
            PopItemFlag();
17161
0
        }
17162
0
    }
17163
17164
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17165
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17166
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17167
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17168
0
    {
17169
        // AllowOverlap mode required for appending into dock node tab bar,
17170
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17171
0
        bool held;
17172
0
        KeepAliveID(title_bar_id);
17173
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17174
0
        if (g.HoveredId == title_bar_id)
17175
0
        {
17176
0
            g.LastItemData.ID = title_bar_id;
17177
0
        }
17178
0
        if (held)
17179
0
        {
17180
0
            if (IsMouseClicked(0))
17181
0
                focus_tab_id = tab_bar->SelectedTabId;
17182
17183
            // Forward moving request to selected window
17184
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17185
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17186
0
        }
17187
0
    }
17188
17189
    // Forward focus from host node to selected window
17190
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17191
    //    focus_tab_id = tab_bar->SelectedTabId;
17192
17193
    // When clicked on a tab we requested focus to the docked child
17194
    // This overrides the value set by "forward focus from host node to selected window".
17195
0
    if (tab_bar->NextSelectedTabId)
17196
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17197
17198
    // Apply navigation focus
17199
0
    if (focus_tab_id != 0)
17200
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17201
0
            if (tab->Window)
17202
0
            {
17203
0
                FocusWindow(tab->Window);
17204
0
                NavInitWindow(tab->Window, false);
17205
0
            }
17206
17207
0
    EndTabBar();
17208
0
    PopID();
17209
17210
    // Restore SkipItems flag
17211
0
    if (!node->IsDockSpace())
17212
0
    {
17213
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17214
0
        host_window->SkipItems = backup_skip_item;
17215
0
    }
17216
0
}
17217
17218
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17219
0
{
17220
0
    IM_ASSERT(node->TabBar == NULL);
17221
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17222
0
}
17223
17224
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17225
0
{
17226
0
    if (node->TabBar == NULL)
17227
0
        return;
17228
0
    IM_DELETE(node->TabBar);
17229
0
    node->TabBar = NULL;
17230
0
}
17231
17232
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17233
85
{
17234
85
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17235
0
        return false;
17236
17237
85
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17238
85
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17239
85
    if (host_class->ClassId != payload_class->ClassId)
17240
0
    {
17241
0
        bool pass = false;
17242
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17243
0
            pass = true;
17244
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17245
0
            pass = true;
17246
0
        if (!pass)
17247
0
            return false;
17248
0
    }
17249
17250
    // Prevent docking any window created above a popup
17251
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17252
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17253
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17254
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17255
85
    ImGuiContext& g = *GImGui;
17256
85
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17257
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17258
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17259
0
                return false;
17260
17261
85
    return true;
17262
85
}
17263
17264
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17265
85
{
17266
85
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17267
0
        return true;
17268
17269
85
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17270
85
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17271
85
    {
17272
85
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17273
85
        if (DockNodeIsDropAllowedOne(payload, host_window))
17274
85
            return true;
17275
85
    }
17276
0
    return false;
17277
85
}
17278
17279
// window menu button == collapse button when not in a dock node.
17280
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17281
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17282
0
{
17283
0
    ImGuiContext& g = *GImGui;
17284
0
    ImGuiStyle& style = g.Style;
17285
17286
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17287
0
    if (out_title_rect) { *out_title_rect = r; }
17288
17289
0
    r.Min.x += style.WindowBorderSize;
17290
0
    r.Max.x -= style.WindowBorderSize;
17291
17292
0
    float button_sz = g.FontSize;
17293
0
    r.Min.x += style.FramePadding.x;
17294
0
    r.Max.x -= style.FramePadding.x;
17295
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17296
0
    if (node->HasCloseButton)
17297
0
    {
17298
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17299
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17300
0
    }
17301
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17302
0
    {
17303
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17304
0
    }
17305
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17306
0
    {
17307
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17308
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17309
0
    }
17310
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17311
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17312
0
}
17313
17314
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17315
0
{
17316
0
    ImGuiContext& g = *GImGui;
17317
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17318
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17319
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17320
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17321
17322
    // Distribute size on given axis (with a desired size or equally)
17323
0
    const float w_avail = size_old[axis] - dock_spacing;
17324
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17325
0
    {
17326
0
        size_new[axis] = size_new_desired[axis];
17327
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17328
0
    }
17329
0
    else
17330
0
    {
17331
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17332
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17333
0
    }
17334
17335
    // Position each node
17336
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17337
0
    {
17338
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17339
0
    }
17340
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17341
0
    {
17342
0
        pos_new[axis] = pos_old[axis];
17343
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17344
0
    }
17345
0
}
17346
17347
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17348
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17349
0
{
17350
0
    ImGuiContext& g = *GImGui;
17351
17352
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17353
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17354
0
    float hs_w; // Half-size, longer axis
17355
0
    float hs_h; // Half-size, smaller axis
17356
0
    ImVec2 off; // Distance from edge or center
17357
0
    if (outer_docking)
17358
0
    {
17359
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17360
        //hs_h = ImTrunc(hs_w * 0.15f);
17361
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17362
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17363
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17364
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17365
0
    }
17366
0
    else
17367
0
    {
17368
0
        hs_w = ImTrunc(hs_for_central_nodes);
17369
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17370
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17371
0
    }
17372
17373
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17374
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17375
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17376
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17377
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17378
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17379
17380
0
    if (test_mouse_pos == NULL)
17381
0
        return false;
17382
17383
0
    ImRect hit_r = out_r;
17384
0
    if (!outer_docking)
17385
0
    {
17386
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17387
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17388
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17389
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17390
0
        float r_threshold_center = hs_w * 1.4f;
17391
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17392
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17393
0
            return (dir == ImGuiDir_None);
17394
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17395
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17396
0
    }
17397
0
    return hit_r.Contains(*test_mouse_pos);
17398
0
}
17399
17400
// host_node may be NULL if the window doesn't have a DockNode already.
17401
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17402
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17403
0
{
17404
0
    ImGuiContext& g = *GImGui;
17405
17406
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17407
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17408
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17409
0
    if (payload_node == NULL)
17410
0
        payload_node = payload_window->DockNodeAsHost;
17411
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17412
0
    if (ref_node_for_rect)
17413
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17414
17415
    // Filter, figure out where we are allowed to dock
17416
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17417
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17418
0
    data->IsCenterAvailable = true;
17419
0
    if (is_outer_docking)
17420
0
        data->IsCenterAvailable = false;
17421
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17422
0
        data->IsCenterAvailable = false;
17423
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17424
0
        data->IsCenterAvailable = false;
17425
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17426
0
        data->IsCenterAvailable = false;
17427
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17428
0
        data->IsCenterAvailable = false;
17429
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17430
0
        data->IsCenterAvailable = false;
17431
17432
0
    data->IsSidesAvailable = true;
17433
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17434
0
        data->IsSidesAvailable = false;
17435
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17436
0
        data->IsSidesAvailable = false;
17437
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17438
0
        data->IsSidesAvailable = false;
17439
17440
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17441
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17442
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17443
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17444
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17445
17446
    // Calculate drop shapes geometry for allowed splitting directions
17447
0
    IM_ASSERT(ImGuiDir_None == -1);
17448
0
    data->SplitNode = host_node;
17449
0
    data->SplitDir = ImGuiDir_None;
17450
0
    data->IsSplitDirExplicit = false;
17451
0
    if (!host_window->Collapsed)
17452
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17453
0
        {
17454
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17455
0
                continue;
17456
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17457
0
                continue;
17458
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17459
0
            {
17460
0
                data->SplitDir = (ImGuiDir)dir;
17461
0
                data->IsSplitDirExplicit = true;
17462
0
            }
17463
0
        }
17464
17465
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17466
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17467
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17468
0
        data->IsDropAllowed = false;
17469
17470
    // Calculate split area
17471
0
    data->SplitRatio = 0.0f;
17472
0
    if (data->SplitDir != ImGuiDir_None)
17473
0
    {
17474
0
        ImGuiDir split_dir = data->SplitDir;
17475
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17476
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17477
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17478
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17479
17480
        // Calculate split ratio so we can pass it down the docking request
17481
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17482
0
        data->FutureNode.Pos = pos_new;
17483
0
        data->FutureNode.Size = size_new;
17484
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17485
0
    }
17486
0
}
17487
17488
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17489
0
{
17490
0
    ImGuiContext& g = *GImGui;
17491
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17492
17493
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17494
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17495
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17496
17497
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17498
0
    int overlay_draw_lists_count = 0;
17499
0
    ImDrawList* overlay_draw_lists[2];
17500
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17501
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17502
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17503
17504
    // Draw main preview rectangle
17505
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17506
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17507
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17508
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17509
17510
    // Display area preview
17511
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17512
0
    if (data->IsDropAllowed)
17513
0
    {
17514
0
        ImRect overlay_rect = data->FutureNode.Rect();
17515
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17516
0
            overlay_rect.Min.y += GetFrameHeight();
17517
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17518
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17519
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17520
0
    }
17521
17522
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17523
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17524
0
    {
17525
        // Compute target tab bar geometry so we can locate our preview tabs
17526
0
        ImRect tab_bar_rect;
17527
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17528
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17529
0
        if (host_node && host_node->TabBar)
17530
0
        {
17531
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17532
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17533
0
            else
17534
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17535
0
        }
17536
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17537
0
        {
17538
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17539
0
        }
17540
17541
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17542
0
        if (root_payload->DockNodeAsHost)
17543
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17544
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17545
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17546
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17547
0
        {
17548
            // DockNode's TabBar may have non-window Tabs manually appended by user
17549
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17550
0
            if (tab_bar_with_payload && payload_window == NULL)
17551
0
                continue;
17552
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17553
0
                continue;
17554
17555
            // Calculate the tab bounding box for each payload window
17556
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17557
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17558
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17559
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17560
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17561
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17562
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17563
0
            {
17564
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17565
0
                if (!tab_bar_rect.Contains(tab_bb))
17566
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17567
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17568
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17569
0
                if (!tab_bar_rect.Contains(tab_bb))
17570
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17571
0
            }
17572
0
            PopStyleColor();
17573
0
        }
17574
0
    }
17575
17576
    // Display drop boxes
17577
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17578
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17579
0
    {
17580
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17581
0
        {
17582
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17583
0
            ImRect draw_r_in = draw_r;
17584
0
            draw_r_in.Expand(-2.0f);
17585
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17586
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17587
0
            {
17588
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17589
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17590
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17591
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17592
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17593
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17594
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17595
0
            }
17596
0
        }
17597
17598
        // Stop after ImGuiDir_None
17599
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17600
0
            return;
17601
0
    }
17602
0
}
17603
17604
//-----------------------------------------------------------------------------
17605
// Docking: ImGuiDockNode Tree manipulation functions
17606
//-----------------------------------------------------------------------------
17607
// - DockNodeTreeSplit()
17608
// - DockNodeTreeMerge()
17609
// - DockNodeTreeUpdatePosSize()
17610
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17611
// - DockNodeTreeUpdateSplitter()
17612
// - DockNodeTreeFindFallbackLeafNode()
17613
// - DockNodeTreeFindNodeByPos()
17614
//-----------------------------------------------------------------------------
17615
17616
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17617
0
{
17618
0
    ImGuiContext& g = *GImGui;
17619
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17620
17621
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17622
0
    child_0->ParentNode = parent_node;
17623
17624
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17625
0
    child_1->ParentNode = parent_node;
17626
17627
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17628
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17629
0
    parent_node->ChildNodes[0] = child_0;
17630
0
    parent_node->ChildNodes[1] = child_1;
17631
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17632
0
    parent_node->SplitAxis = split_axis;
17633
0
    parent_node->VisibleWindow = NULL;
17634
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17635
17636
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17637
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17638
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17639
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17640
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17641
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17642
17643
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17644
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17645
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17646
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17647
17648
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17649
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17650
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17651
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17652
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17653
0
    child_0->UpdateMergedFlags();
17654
0
    child_1->UpdateMergedFlags();
17655
0
    parent_node->UpdateMergedFlags();
17656
0
    if (child_inheritor->IsCentralNode())
17657
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17658
0
}
17659
17660
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17661
0
{
17662
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17663
0
    ImGuiContext& g = *GImGui;
17664
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17665
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17666
0
    IM_ASSERT(child_0 || child_1);
17667
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17668
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17669
0
    {
17670
0
        IM_ASSERT(parent_node->TabBar == NULL);
17671
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17672
0
    }
17673
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17674
17675
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17676
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17677
0
    if (child_0)
17678
0
    {
17679
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17680
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17681
0
    }
17682
0
    if (child_1)
17683
0
    {
17684
0
        DockNodeMoveWindows(parent_node, child_1);
17685
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17686
0
    }
17687
0
    DockNodeApplyPosSizeToWindows(parent_node);
17688
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17689
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17690
0
    parent_node->SizeRef = backup_last_explicit_size;
17691
17692
    // Flags transfer
17693
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17694
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17695
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17696
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17697
0
    parent_node->UpdateMergedFlags();
17698
17699
0
    if (child_0)
17700
0
    {
17701
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17702
0
        IM_DELETE(child_0);
17703
0
    }
17704
0
    if (child_1)
17705
0
    {
17706
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17707
0
        IM_DELETE(child_1);
17708
0
    }
17709
0
}
17710
17711
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17712
// (Depth-first, Pre-Order)
17713
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17714
0
{
17715
    // During the regular dock node update we write to all nodes.
17716
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17717
0
    ImGuiContext& g = *GImGui;
17718
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17719
0
    if (write_to_node)
17720
0
    {
17721
0
        node->Pos = pos;
17722
0
        node->Size = size;
17723
0
    }
17724
17725
0
    if (node->IsLeafNode())
17726
0
        return;
17727
17728
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17729
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17730
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17731
0
    ImVec2 child_0_size = size, child_1_size = size;
17732
17733
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17734
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17735
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17736
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17737
17738
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17739
0
    {
17740
0
        const float spacing = g.Style.DockingSeparatorSize;
17741
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17742
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17743
17744
        // Size allocation policy
17745
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17746
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17747
17748
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17749
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
17750
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17751
17752
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17753
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17754
0
        {
17755
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17756
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17757
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17758
0
        }
17759
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17760
0
        {
17761
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17762
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17763
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17764
0
        }
17765
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17766
0
        {
17767
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17768
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17769
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17770
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
17771
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17772
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17773
0
        }
17774
17775
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17776
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17777
0
        {
17778
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17779
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17780
0
        }
17781
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17782
0
        {
17783
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17784
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17785
0
        }
17786
0
        else
17787
0
        {
17788
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17789
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17790
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
17791
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17792
0
        }
17793
17794
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17795
0
    }
17796
17797
0
    if (only_write_to_single_node == NULL)
17798
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17799
17800
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17801
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17802
0
    if (child_0_recurse)
17803
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17804
0
    if (child_1_recurse)
17805
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17806
0
}
17807
17808
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17809
0
{
17810
0
    if (node->IsLeafNode())
17811
0
    {
17812
0
        touching_nodes->push_back(node);
17813
0
        return;
17814
0
    }
17815
0
    if (node->ChildNodes[0]->IsVisible)
17816
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17817
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17818
0
    if (node->ChildNodes[1]->IsVisible)
17819
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17820
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17821
0
}
17822
17823
// (Depth-First, Pre-Order)
17824
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17825
0
{
17826
0
    if (node->IsLeafNode())
17827
0
        return;
17828
17829
0
    ImGuiContext& g = *GImGui;
17830
17831
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17832
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17833
0
    if (child_0->IsVisible && child_1->IsVisible)
17834
0
    {
17835
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17836
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17837
0
        IM_ASSERT(axis != ImGuiAxis_None);
17838
0
        ImRect bb;
17839
0
        bb.Min = child_0->Pos;
17840
0
        bb.Max = child_1->Pos;
17841
0
        bb.Min[axis] += child_0->Size[axis];
17842
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17843
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17844
17845
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17846
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17847
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17848
0
        {
17849
0
            ImGuiWindow* window = g.CurrentWindow;
17850
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17851
0
        }
17852
0
        else
17853
0
        {
17854
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17855
            //bb.Max[axis] -= 1;
17856
0
            PushID(node->ID);
17857
17858
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17859
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17860
0
            float min_size = g.Style.WindowMinSize[axis];
17861
0
            float resize_limits[2];
17862
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17863
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17864
17865
0
            ImGuiID splitter_id = GetID("##Splitter");
17866
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17867
0
            {
17868
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17869
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17870
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17871
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17872
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17873
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17874
17875
                // [DEBUG] Render touching nodes & limits
17876
                /*
17877
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17878
                for (int n = 0; n < 2; n++)
17879
                {
17880
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17881
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17882
                    if (axis == ImGuiAxis_X)
17883
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17884
                    else
17885
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17886
                }
17887
                */
17888
0
            }
17889
17890
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17891
0
            float cur_size_0 = child_0->Size[axis];
17892
0
            float cur_size_1 = child_1->Size[axis];
17893
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17894
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17895
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17896
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17897
0
            {
17898
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17899
0
                {
17900
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17901
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17902
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17903
17904
                    // Lock the size of every node that is a sibling of the node we are touching
17905
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17906
0
                    for (int side_n = 0; side_n < 2; side_n++)
17907
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17908
0
                        {
17909
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17910
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17911
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17912
0
                            while (touching_node->ParentNode != node)
17913
0
                            {
17914
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17915
0
                                {
17916
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17917
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17918
0
                                    node_to_preserve->WantLockSizeOnce = true;
17919
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17920
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17921
0
                                }
17922
0
                                touching_node = touching_node->ParentNode;
17923
0
                            }
17924
0
                        }
17925
17926
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17927
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17928
0
                    MarkIniSettingsDirty();
17929
0
                }
17930
0
            }
17931
0
            PopID();
17932
0
        }
17933
0
    }
17934
17935
0
    if (child_0->IsVisible)
17936
0
        DockNodeTreeUpdateSplitter(child_0);
17937
0
    if (child_1->IsVisible)
17938
0
        DockNodeTreeUpdateSplitter(child_1);
17939
0
}
17940
17941
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17942
0
{
17943
0
    if (node->IsLeafNode())
17944
0
        return node;
17945
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17946
0
        return leaf_node;
17947
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17948
0
        return leaf_node;
17949
0
    return NULL;
17950
0
}
17951
17952
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17953
0
{
17954
0
    if (!node->IsVisible)
17955
0
        return NULL;
17956
17957
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17958
0
    ImRect r(node->Pos, node->Pos + node->Size);
17959
0
    r.Expand(dock_spacing * 0.5f);
17960
0
    bool inside = r.Contains(pos);
17961
0
    if (!inside)
17962
0
        return NULL;
17963
17964
0
    if (node->IsLeafNode())
17965
0
        return node;
17966
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17967
0
        return hovered_node;
17968
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17969
0
        return hovered_node;
17970
17971
    // This means we are hovering over the splitter/spacing of a parent node
17972
0
    return node;
17973
0
}
17974
17975
//-----------------------------------------------------------------------------
17976
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17977
//-----------------------------------------------------------------------------
17978
// - SetWindowDock() [Internal]
17979
// - DockSpace()
17980
// - DockSpaceOverViewport()
17981
//-----------------------------------------------------------------------------
17982
17983
// [Internal] Called via SetNextWindowDockID()
17984
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17985
0
{
17986
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17987
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17988
0
        return;
17989
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17990
17991
0
    if (window->DockId == dock_id)
17992
0
        return;
17993
17994
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17995
0
    ImGuiContext& g = *GImGui;
17996
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
17997
0
        if (new_node->IsSplitNode())
17998
0
        {
17999
            // Policy: Find central node or latest focused node. We first move back to our root node.
18000
0
            new_node = DockNodeGetRootNode(new_node);
18001
0
            if (new_node->CentralNode)
18002
0
            {
18003
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18004
0
                dock_id = new_node->CentralNode->ID;
18005
0
            }
18006
0
            else
18007
0
            {
18008
0
                dock_id = new_node->LastFocusedNodeId;
18009
0
            }
18010
0
        }
18011
18012
0
    if (window->DockId == dock_id)
18013
0
        return;
18014
18015
0
    if (window->DockNode)
18016
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18017
0
    window->DockId = dock_id;
18018
0
}
18019
18020
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18021
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18022
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18023
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18024
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18025
0
{
18026
0
    ImGuiContext& g = *GImGui;
18027
0
    ImGuiWindow* window = GetCurrentWindowRead();
18028
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18029
0
        return 0;
18030
18031
    // Early out if parent window is hidden/collapsed
18032
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18033
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18034
0
    if (window->SkipItems)
18035
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18036
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18037
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18038
18039
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18040
0
    IM_ASSERT(id != 0);
18041
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18042
0
    if (!node)
18043
0
    {
18044
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18045
0
        node = DockContextAddNode(&g, id);
18046
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18047
0
    }
18048
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18049
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18050
0
    node->SharedFlags = flags;
18051
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18052
18053
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18054
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18055
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18056
0
    {
18057
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18058
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18059
0
        return id;
18060
0
    }
18061
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18062
18063
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18064
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18065
0
    {
18066
0
        node->LastFrameAlive = g.FrameCount;
18067
0
        return id;
18068
0
    }
18069
18070
0
    const ImVec2 content_avail = GetContentRegionAvail();
18071
0
    ImVec2 size = ImTrunc(size_arg);
18072
0
    if (size.x <= 0.0f)
18073
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18074
0
    if (size.y <= 0.0f)
18075
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18076
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18077
18078
0
    node->Pos = window->DC.CursorPos;
18079
0
    node->Size = node->SizeRef = size;
18080
0
    SetNextWindowPos(node->Pos);
18081
0
    SetNextWindowSize(node->Size);
18082
0
    g.NextWindowData.PosUndock = false;
18083
18084
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18085
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18086
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18087
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18088
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18089
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18090
18091
0
    char title[256];
18092
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18093
18094
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18095
0
    Begin(title, NULL, window_flags);
18096
0
    PopStyleVar();
18097
18098
0
    ImGuiWindow* host_window = g.CurrentWindow;
18099
0
    DockNodeSetupHostWindow(node, host_window);
18100
0
    host_window->ChildId = window->GetID(title);
18101
0
    node->OnlyNodeWithWindows = NULL;
18102
18103
0
    IM_ASSERT(node->IsRootNode());
18104
18105
    // We need to handle the rare case were a central node is missing.
18106
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18107
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18108
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18109
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18110
    // as it doesn't make sense for an empty dockspace to not have this property.
18111
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18112
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18113
18114
    // Update the node
18115
0
    DockNodeUpdate(node);
18116
18117
0
    End();
18118
18119
0
    ImRect bb(node->Pos, node->Pos + size);
18120
0
    ItemSize(size);
18121
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18122
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18123
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18124
18125
0
    return id;
18126
0
}
18127
18128
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18129
// The limitation with this call is that your window won't have a menu bar.
18130
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18131
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18132
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18133
0
{
18134
0
    if (viewport == NULL)
18135
0
        viewport = GetMainViewport();
18136
18137
0
    SetNextWindowPos(viewport->WorkPos);
18138
0
    SetNextWindowSize(viewport->WorkSize);
18139
0
    SetNextWindowViewport(viewport->ID);
18140
18141
0
    ImGuiWindowFlags host_window_flags = 0;
18142
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18143
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18144
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18145
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18146
18147
0
    char label[32];
18148
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18149
18150
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18151
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18152
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18153
0
    Begin(label, NULL, host_window_flags);
18154
0
    PopStyleVar(3);
18155
18156
0
    ImGuiID dockspace_id = GetID("DockSpace");
18157
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18158
0
    End();
18159
18160
0
    return dockspace_id;
18161
0
}
18162
18163
//-----------------------------------------------------------------------------
18164
// Docking: Builder Functions
18165
//-----------------------------------------------------------------------------
18166
// Very early end-user API to manipulate dock nodes.
18167
// Only available in imgui_internal.h. Expect this API to change/break!
18168
// It is expected that those functions are all called _before_ the dockspace node submission.
18169
//-----------------------------------------------------------------------------
18170
// - DockBuilderDockWindow()
18171
// - DockBuilderGetNode()
18172
// - DockBuilderSetNodePos()
18173
// - DockBuilderSetNodeSize()
18174
// - DockBuilderAddNode()
18175
// - DockBuilderRemoveNode()
18176
// - DockBuilderRemoveNodeChildNodes()
18177
// - DockBuilderRemoveNodeDockedWindows()
18178
// - DockBuilderSplitNode()
18179
// - DockBuilderCopyNodeRec()
18180
// - DockBuilderCopyNode()
18181
// - DockBuilderCopyWindowSettings()
18182
// - DockBuilderCopyDockSpace()
18183
// - DockBuilderFinish()
18184
//-----------------------------------------------------------------------------
18185
18186
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18187
0
{
18188
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18189
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18190
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18191
0
    ImGuiID window_id = ImHashStr(window_name);
18192
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18193
0
    {
18194
        // Apply to created window
18195
0
        ImGuiID prev_node_id = window->DockId;
18196
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18197
0
        if (window->DockId != prev_node_id)
18198
0
            window->DockOrder = -1;
18199
0
    }
18200
0
    else
18201
0
    {
18202
        // Apply to settings
18203
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18204
0
        if (settings == NULL)
18205
0
            settings = CreateNewWindowSettings(window_name);
18206
0
        if (settings->DockId != node_id)
18207
0
            settings->DockOrder = -1;
18208
0
        settings->DockId = node_id;
18209
0
    }
18210
0
}
18211
18212
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18213
0
{
18214
0
    ImGuiContext& g = *GImGui;
18215
0
    return DockContextFindNodeByID(&g, node_id);
18216
0
}
18217
18218
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18219
0
{
18220
0
    ImGuiContext& g = *GImGui;
18221
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18222
0
    if (node == NULL)
18223
0
        return;
18224
0
    node->Pos = pos;
18225
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18226
0
}
18227
18228
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18229
0
{
18230
0
    ImGuiContext& g = *GImGui;
18231
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18232
0
    if (node == NULL)
18233
0
        return;
18234
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18235
0
    node->Size = node->SizeRef = size;
18236
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18237
0
}
18238
18239
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18240
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18241
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18242
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18243
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18244
// - Use (id == 0) to let the system allocate a node identifier.
18245
// - Existing node with a same id will be removed.
18246
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18247
0
{
18248
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18249
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18250
18251
0
    if (node_id != 0)
18252
0
        DockBuilderRemoveNode(node_id);
18253
18254
0
    ImGuiDockNode* node = NULL;
18255
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18256
0
    {
18257
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18258
0
        node = DockContextFindNodeByID(&g, node_id);
18259
0
    }
18260
0
    else
18261
0
    {
18262
0
        node = DockContextAddNode(&g, node_id);
18263
0
        node->SetLocalFlags(flags);
18264
0
    }
18265
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18266
0
    return node->ID;
18267
0
}
18268
18269
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18270
0
{
18271
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18272
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18273
18274
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18275
0
    if (node == NULL)
18276
0
        return;
18277
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18278
0
    DockBuilderRemoveNodeChildNodes(node_id);
18279
    // Node may have moved or deleted if e.g. any merge happened
18280
0
    node = DockContextFindNodeByID(&g, node_id);
18281
0
    if (node == NULL)
18282
0
        return;
18283
0
    if (node->IsCentralNode() && node->ParentNode)
18284
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18285
0
    DockContextRemoveNode(&g, node, true);
18286
0
}
18287
18288
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18289
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18290
0
{
18291
0
    ImGuiContext& g = *GImGui;
18292
0
    ImGuiDockContext* dc = &g.DockContext;
18293
18294
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
18295
0
    if (root_id && root_node == NULL)
18296
0
        return;
18297
0
    bool has_central_node = false;
18298
18299
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18300
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18301
18302
    // Process active windows
18303
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18304
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18305
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18306
0
        {
18307
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18308
0
            if (want_removal)
18309
0
            {
18310
0
                if (node->IsCentralNode())
18311
0
                    has_central_node = true;
18312
0
                if (root_id != 0)
18313
0
                    DockContextQueueNotifyRemovedNode(&g, node);
18314
0
                if (root_node)
18315
0
                {
18316
0
                    DockNodeMoveWindows(root_node, node);
18317
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18318
0
                }
18319
0
                nodes_to_remove.push_back(node);
18320
0
            }
18321
0
        }
18322
18323
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18324
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18325
0
    if (root_node)
18326
0
    {
18327
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18328
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18329
0
    }
18330
18331
    // Apply to settings
18332
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18333
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18334
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18335
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18336
0
                {
18337
0
                    settings->DockId = root_id;
18338
0
                    break;
18339
0
                }
18340
18341
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18342
0
    if (nodes_to_remove.Size > 1)
18343
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18344
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18345
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
18346
18347
0
    if (root_id == 0)
18348
0
    {
18349
0
        dc->Nodes.Clear();
18350
0
        dc->Requests.clear();
18351
0
    }
18352
0
    else if (has_central_node)
18353
0
    {
18354
0
        root_node->CentralNode = root_node;
18355
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18356
0
    }
18357
0
}
18358
18359
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18360
0
{
18361
    // Clear references in settings
18362
0
    ImGuiContext& g = *GImGui;
18363
0
    if (clear_settings_refs)
18364
0
    {
18365
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18366
0
        {
18367
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18368
0
            if (!want_removal && settings->DockId != 0)
18369
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
18370
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18371
0
                        want_removal = true;
18372
0
            if (want_removal)
18373
0
                settings->DockId = 0;
18374
0
        }
18375
0
    }
18376
18377
    // Clear references in windows
18378
0
    for (int n = 0; n < g.Windows.Size; n++)
18379
0
    {
18380
0
        ImGuiWindow* window = g.Windows[n];
18381
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18382
0
        if (want_removal)
18383
0
        {
18384
0
            const ImGuiID backup_dock_id = window->DockId;
18385
0
            IM_UNUSED(backup_dock_id);
18386
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
18387
0
            if (!clear_settings_refs)
18388
0
                IM_ASSERT(window->DockId == backup_dock_id);
18389
0
        }
18390
0
    }
18391
0
}
18392
18393
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18394
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18395
// FIXME-DOCK: We are not exposing nor using split_outer.
18396
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18397
0
{
18398
0
    ImGuiContext& g = *GImGui;
18399
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18400
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18401
18402
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18403
0
    if (node == NULL)
18404
0
    {
18405
0
        IM_ASSERT(node != NULL);
18406
0
        return 0;
18407
0
    }
18408
18409
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18410
18411
0
    ImGuiDockRequest req;
18412
0
    req.Type = ImGuiDockRequestType_Split;
18413
0
    req.DockTargetWindow = NULL;
18414
0
    req.DockTargetNode = node;
18415
0
    req.DockPayload = NULL;
18416
0
    req.DockSplitDir = split_dir;
18417
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18418
0
    req.DockSplitOuter = false;
18419
0
    DockContextProcessDock(&g, &req);
18420
18421
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18422
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18423
0
    if (out_id_at_dir)
18424
0
        *out_id_at_dir = id_at_dir;
18425
0
    if (out_id_at_opposite_dir)
18426
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18427
0
    return id_at_dir;
18428
0
}
18429
18430
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18431
0
{
18432
0
    ImGuiContext& g = *GImGui;
18433
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18434
0
    dst_node->SharedFlags = src_node->SharedFlags;
18435
0
    dst_node->LocalFlags = src_node->LocalFlags;
18436
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18437
0
    dst_node->Pos = src_node->Pos;
18438
0
    dst_node->Size = src_node->Size;
18439
0
    dst_node->SizeRef = src_node->SizeRef;
18440
0
    dst_node->SplitAxis = src_node->SplitAxis;
18441
0
    dst_node->UpdateMergedFlags();
18442
18443
0
    out_node_remap_pairs->push_back(src_node->ID);
18444
0
    out_node_remap_pairs->push_back(dst_node->ID);
18445
18446
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18447
0
        if (src_node->ChildNodes[child_n])
18448
0
        {
18449
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18450
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18451
0
        }
18452
18453
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18454
0
    return dst_node;
18455
0
}
18456
18457
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18458
0
{
18459
0
    ImGuiContext& g = *GImGui;
18460
0
    IM_ASSERT(src_node_id != 0);
18461
0
    IM_ASSERT(dst_node_id != 0);
18462
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18463
18464
0
    DockBuilderRemoveNode(dst_node_id);
18465
18466
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
18467
0
    IM_ASSERT(src_node != NULL);
18468
18469
0
    out_node_remap_pairs->clear();
18470
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18471
18472
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18473
0
}
18474
18475
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18476
0
{
18477
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18478
0
    if (src_window == NULL)
18479
0
        return;
18480
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18481
0
    {
18482
0
        dst_window->Pos = src_window->Pos;
18483
0
        dst_window->Size = src_window->Size;
18484
0
        dst_window->SizeFull = src_window->SizeFull;
18485
0
        dst_window->Collapsed = src_window->Collapsed;
18486
0
    }
18487
0
    else
18488
0
    {
18489
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18490
0
        if (!dst_settings)
18491
0
            dst_settings = CreateNewWindowSettings(dst_name);
18492
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18493
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18494
0
        {
18495
0
            dst_settings->ViewportPos = window_pos_2ih;
18496
0
            dst_settings->ViewportId = src_window->ViewportId;
18497
0
            dst_settings->Pos = ImVec2ih(0, 0);
18498
0
        }
18499
0
        else
18500
0
        {
18501
0
            dst_settings->Pos = window_pos_2ih;
18502
0
        }
18503
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18504
0
        dst_settings->Collapsed = src_window->Collapsed;
18505
0
    }
18506
0
}
18507
18508
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18509
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18510
0
{
18511
0
    ImGuiContext& g = *GImGui;
18512
0
    IM_ASSERT(src_dockspace_id != 0);
18513
0
    IM_ASSERT(dst_dockspace_id != 0);
18514
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18515
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18516
18517
    // Duplicate entire dock
18518
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18519
    // whereas we could attempt to at least keep them together in a new, same floating node.
18520
0
    ImVector<ImGuiID> node_remap_pairs;
18521
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18522
18523
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18524
    // (The windows associated to src_dockspace_id are staying in place)
18525
0
    ImVector<ImGuiID> src_windows;
18526
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18527
0
    {
18528
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18529
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18530
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18531
0
        src_windows.push_back(src_window_id);
18532
18533
        // Search in the remapping tables
18534
0
        ImGuiID src_dock_id = 0;
18535
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18536
0
            src_dock_id = src_window->DockId;
18537
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18538
0
            src_dock_id = src_window_settings->DockId;
18539
0
        ImGuiID dst_dock_id = 0;
18540
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18541
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18542
0
            {
18543
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18544
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18545
0
                break;
18546
0
            }
18547
18548
0
        if (dst_dock_id != 0)
18549
0
        {
18550
            // Docked windows gets redocked into the new node hierarchy.
18551
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18552
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18553
0
        }
18554
0
        else
18555
0
        {
18556
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18557
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18558
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18559
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18560
0
        }
18561
0
    }
18562
18563
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18564
    // Find those windows and move to them to the cloned dock node. This may be optional?
18565
    // Dock those are a second step as undocking would invalidate source dock nodes.
18566
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18567
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18568
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18569
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18570
0
        {
18571
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18572
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18573
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18574
0
            {
18575
0
                ImGuiWindow* window = node->Windows[window_n];
18576
0
                if (src_windows.contains(window->ID))
18577
0
                    continue;
18578
18579
                // Docked windows gets redocked into the new node hierarchy.
18580
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18581
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18582
0
            }
18583
0
        }
18584
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18585
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18586
0
}
18587
18588
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18589
void ImGui::DockBuilderFinish(ImGuiID root_id)
18590
0
{
18591
0
    ImGuiContext& g = *GImGui;
18592
    //DockContextRebuild(&g);
18593
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
18594
0
}
18595
18596
//-----------------------------------------------------------------------------
18597
// Docking: Begin/End Support Functions (called from Begin/End)
18598
//-----------------------------------------------------------------------------
18599
// - GetWindowAlwaysWantOwnTabBar()
18600
// - DockContextBindNodeToWindow()
18601
// - BeginDocked()
18602
// - BeginDockableDragDropSource()
18603
// - BeginDockableDragDropTarget()
18604
//-----------------------------------------------------------------------------
18605
18606
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18607
188k
{
18608
188k
    ImGuiContext& g = *GImGui;
18609
188k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18610
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18611
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18612
0
                return true;
18613
188k
    return false;
18614
188k
}
18615
18616
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18617
0
{
18618
0
    ImGuiContext& g = *ctx;
18619
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18620
0
    IM_ASSERT(window->DockNode == NULL);
18621
18622
    // We should not be docking into a split node (SetWindowDock should avoid this)
18623
0
    if (node && node->IsSplitNode())
18624
0
    {
18625
0
        DockContextProcessUndockWindow(ctx, window);
18626
0
        return NULL;
18627
0
    }
18628
18629
    // Create node
18630
0
    if (node == NULL)
18631
0
    {
18632
0
        node = DockContextAddNode(ctx, window->DockId);
18633
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18634
0
        node->LastFrameAlive = g.FrameCount;
18635
0
    }
18636
18637
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18638
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18639
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18640
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18641
0
    if (!node->IsVisible)
18642
0
    {
18643
0
        ImGuiDockNode* ancestor_node = node;
18644
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18645
0
            ancestor_node = ancestor_node->ParentNode;
18646
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18647
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18648
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18649
0
    }
18650
18651
    // Add window to node
18652
0
    bool node_was_visible = node->IsVisible;
18653
0
    DockNodeAddWindow(node, window, true);
18654
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18655
0
    IM_ASSERT(node == window->DockNode);
18656
0
    return node;
18657
0
}
18658
18659
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18660
0
{
18661
0
    ImGuiContext& g = *GImGui;
18662
18663
    // Clear fields ahead so most early-out paths don't have to do it
18664
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18665
18666
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18667
0
    if (auto_dock_node)
18668
0
    {
18669
0
        if (window->DockId == 0)
18670
0
        {
18671
0
            IM_ASSERT(window->DockNode == NULL);
18672
0
            window->DockId = DockContextGenNodeID(&g);
18673
0
        }
18674
0
    }
18675
0
    else
18676
0
    {
18677
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18678
0
        bool want_undock = false;
18679
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18680
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18681
0
        if (want_undock)
18682
0
        {
18683
0
            DockContextProcessUndockWindow(&g, window);
18684
0
            return;
18685
0
        }
18686
0
    }
18687
18688
    // Bind to our dock node
18689
0
    ImGuiDockNode* node = window->DockNode;
18690
0
    if (node != NULL)
18691
0
        IM_ASSERT(window->DockId == node->ID);
18692
0
    if (window->DockId != 0 && node == NULL)
18693
0
    {
18694
0
        node = DockContextBindNodeToWindow(&g, window);
18695
0
        if (node == NULL)
18696
0
            return;
18697
0
    }
18698
18699
#if 0
18700
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18701
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18702
    {
18703
        DockContextProcessUndockWindow(ctx, window);
18704
        return;
18705
    }
18706
#endif
18707
18708
    // Undock if our dockspace node disappeared
18709
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18710
0
    if (node->LastFrameAlive < g.FrameCount)
18711
0
    {
18712
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18713
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18714
0
        if (root_node->LastFrameAlive < g.FrameCount)
18715
0
            DockContextProcessUndockWindow(&g, window);
18716
0
        else
18717
0
            window->DockIsActive = true;
18718
0
        return;
18719
0
    }
18720
18721
    // Store style overrides
18722
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18723
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18724
18725
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18726
    // and never create neither a host window neither a tab bar.
18727
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18728
0
    if (node->HostWindow == NULL)
18729
0
    {
18730
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18731
0
            window->DockIsActive = true;
18732
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
18733
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18734
0
        return;
18735
0
    }
18736
18737
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18738
0
    IM_ASSERT(node->HostWindow);
18739
0
    IM_ASSERT(node->IsLeafNode());
18740
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18741
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18742
18743
    // Undock if we are submitted earlier than the host window
18744
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18745
0
    {
18746
0
        DockContextProcessUndockWindow(&g, window);
18747
0
        return;
18748
0
    }
18749
18750
    // Position/Size window
18751
0
    SetNextWindowPos(node->Pos);
18752
0
    SetNextWindowSize(node->Size);
18753
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18754
0
    window->DockIsActive = true;
18755
0
    window->DockNodeIsVisible = true;
18756
0
    window->DockTabIsVisible = false;
18757
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18758
0
        return;
18759
18760
    // When the window is selected we mark it as visible.
18761
0
    if (node->VisibleWindow == window)
18762
0
        window->DockTabIsVisible = true;
18763
18764
    // Update window flag
18765
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18766
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
18767
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
18768
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18769
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18770
0
    else
18771
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18772
18773
    // Save new dock order only if the window has been visible once already
18774
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18775
0
    if (node->TabBar && window->WasActive)
18776
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18777
18778
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18779
0
        *p_open = false;
18780
18781
    // Update ChildId to allow returning from Child to Parent with Escape
18782
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18783
0
    window->ChildId = parent_window->GetID(window->Name);
18784
0
}
18785
18786
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18787
780
{
18788
780
    ImGuiContext& g = *GImGui;
18789
780
    IM_ASSERT(g.ActiveId == window->MoveId);
18790
780
    IM_ASSERT(g.MovingWindow == window);
18791
780
    IM_ASSERT(g.CurrentWindow == window);
18792
18793
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
18794
780
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
18795
0
    {
18796
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
18797
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
18798
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
18799
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
18800
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
18801
0
        return;
18802
0
    }
18803
18804
780
    g.LastItemData.ID = window->MoveId;
18805
780
    window = window->RootWindowDockTree;
18806
780
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18807
780
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18808
780
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18809
425
    {
18810
425
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18811
425
        EndDragDropSource();
18812
18813
        // Store style overrides
18814
2.97k
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18815
2.55k
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18816
425
    }
18817
780
}
18818
18819
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18820
777
{
18821
777
    ImGuiContext& g = *GImGui;
18822
18823
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18824
777
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18825
777
    if (!g.DragDropActive)
18826
0
        return;
18827
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18828
777
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18829
692
        return;
18830
18831
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18832
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18833
85
    const ImGuiPayload* payload = &g.DragDropPayload;
18834
85
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18835
0
    {
18836
0
        EndDragDropTarget();
18837
0
        return;
18838
0
    }
18839
18840
85
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18841
85
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18842
85
    {
18843
        // Select target node
18844
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18845
85
        bool dock_into_floating_window = false;
18846
85
        ImGuiDockNode* node = NULL;
18847
85
        if (window->DockNodeAsHost)
18848
0
        {
18849
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18850
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18851
18852
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18853
            // In this case we need to fallback into any leaf mode, possibly the central node.
18854
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18855
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18856
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18857
0
        }
18858
85
        else
18859
85
        {
18860
85
            if (window->DockNode)
18861
0
                node = window->DockNode;
18862
85
            else
18863
85
                dock_into_floating_window = true; // Dock into a regular window
18864
85
        }
18865
18866
85
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18867
85
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18868
18869
        // Preview docking request and find out split direction/ratio
18870
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18871
85
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18872
85
        if (do_preview && (node != NULL || dock_into_floating_window))
18873
0
        {
18874
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18875
0
            ImGuiDockPreviewData split_inner;
18876
0
            ImGuiDockPreviewData split_outer;
18877
0
            ImGuiDockPreviewData* split_data = &split_inner;
18878
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18879
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18880
0
                {
18881
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18882
0
                    if (split_outer.IsSplitDirExplicit)
18883
0
                        split_data = &split_outer;
18884
0
                }
18885
0
            if (!node || node->IsLeafNode())
18886
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18887
0
            if (split_data == &split_outer)
18888
0
                split_inner.IsDropAllowed = false;
18889
18890
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18891
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18892
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18893
18894
            // Queue docking request
18895
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18896
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18897
0
        }
18898
85
    }
18899
85
    EndDragDropTarget();
18900
85
}
18901
18902
//-----------------------------------------------------------------------------
18903
// Docking: Settings
18904
//-----------------------------------------------------------------------------
18905
// - DockSettingsRenameNodeReferences()
18906
// - DockSettingsRemoveNodeReferences()
18907
// - DockSettingsFindNodeSettings()
18908
// - DockSettingsHandler_ApplyAll()
18909
// - DockSettingsHandler_ReadOpen()
18910
// - DockSettingsHandler_ReadLine()
18911
// - DockSettingsHandler_DockNodeToSettings()
18912
// - DockSettingsHandler_WriteAll()
18913
//-----------------------------------------------------------------------------
18914
18915
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18916
0
{
18917
0
    ImGuiContext& g = *GImGui;
18918
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18919
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18920
0
    {
18921
0
        ImGuiWindow* window = g.Windows[window_n];
18922
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18923
0
            window->DockId = new_node_id;
18924
0
    }
18925
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18926
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18927
0
        if (settings->DockId == old_node_id)
18928
0
            settings->DockId = new_node_id;
18929
0
}
18930
18931
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18932
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18933
0
{
18934
0
    ImGuiContext& g = *GImGui;
18935
0
    int found = 0;
18936
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18937
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18938
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18939
0
            if (settings->DockId == node_ids[node_n])
18940
0
            {
18941
0
                settings->DockId = 0;
18942
0
                settings->DockOrder = -1;
18943
0
                if (++found < node_ids_count)
18944
0
                    break;
18945
0
                return;
18946
0
            }
18947
0
}
18948
18949
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18950
0
{
18951
    // FIXME-OPT
18952
0
    ImGuiDockContext* dc = &ctx->DockContext;
18953
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18954
0
        if (dc->NodesSettings[n].ID == id)
18955
0
            return &dc->NodesSettings[n];
18956
0
    return NULL;
18957
0
}
18958
18959
// Clear settings data
18960
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18961
0
{
18962
0
    ImGuiDockContext* dc = &ctx->DockContext;
18963
0
    dc->NodesSettings.clear();
18964
0
    DockContextClearNodes(ctx, 0, true);
18965
0
}
18966
18967
// Recreate nodes based on settings data
18968
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18969
0
{
18970
    // Prune settings at boot time only
18971
0
    ImGuiDockContext* dc = &ctx->DockContext;
18972
0
    if (ctx->Windows.Size == 0)
18973
0
        DockContextPruneUnusedSettingsNodes(ctx);
18974
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18975
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18976
0
}
18977
18978
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18979
0
{
18980
0
    if (strcmp(name, "Data") != 0)
18981
0
        return NULL;
18982
0
    return (void*)1;
18983
0
}
18984
18985
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18986
0
{
18987
0
    char c = 0;
18988
0
    int x = 0, y = 0;
18989
0
    int r = 0;
18990
18991
    // Parsing, e.g.
18992
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18993
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18994
    // Important: this code expect currently fields in a fixed order.
18995
0
    ImGuiDockNodeSettings node;
18996
0
    line = ImStrSkipBlank(line);
18997
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18998
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18999
0
    else return;
19000
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19001
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19002
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19003
0
    if (node.ParentNodeId == 0)
19004
0
    {
19005
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19006
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19007
0
    }
19008
0
    else
19009
0
    {
19010
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19011
0
    }
19012
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19013
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19014
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19015
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19016
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19017
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19018
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19019
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19020
0
    if (node.ParentNodeId != 0)
19021
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19022
0
            node.Depth = parent_settings->Depth + 1;
19023
0
    ctx->DockContext.NodesSettings.push_back(node);
19024
0
}
19025
19026
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19027
0
{
19028
0
    ImGuiDockNodeSettings node_settings;
19029
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19030
0
    node_settings.ID = node->ID;
19031
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19032
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19033
0
    node_settings.SelectedTabId = node->SelectedTabId;
19034
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19035
0
    node_settings.Depth = (char)depth;
19036
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19037
0
    node_settings.Pos = ImVec2ih(node->Pos);
19038
0
    node_settings.Size = ImVec2ih(node->Size);
19039
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19040
0
    dc->NodesSettings.push_back(node_settings);
19041
0
    if (node->ChildNodes[0])
19042
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19043
0
    if (node->ChildNodes[1])
19044
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19045
0
}
19046
19047
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19048
0
{
19049
0
    ImGuiContext& g = *ctx;
19050
0
    ImGuiDockContext* dc = &ctx->DockContext;
19051
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19052
0
        return;
19053
19054
    // Gather settings data
19055
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19056
0
    dc->NodesSettings.resize(0);
19057
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19058
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19059
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19060
0
            if (node->IsRootNode())
19061
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19062
19063
0
    int max_depth = 0;
19064
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19065
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19066
19067
    // Write to text buffer
19068
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19069
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19070
0
    {
19071
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19072
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19073
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19074
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19075
0
        if (node_settings->ParentNodeId)
19076
0
        {
19077
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19078
0
        }
19079
0
        else
19080
0
        {
19081
0
            if (node_settings->ParentWindowId)
19082
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19083
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19084
0
        }
19085
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19086
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19087
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19088
0
            buf->appendf(" NoResize=1");
19089
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19090
0
            buf->appendf(" CentralNode=1");
19091
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19092
0
            buf->appendf(" NoTabBar=1");
19093
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19094
0
            buf->appendf(" HiddenTabBar=1");
19095
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19096
0
            buf->appendf(" NoWindowMenuButton=1");
19097
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19098
0
            buf->appendf(" NoCloseButton=1");
19099
0
        if (node_settings->SelectedTabId)
19100
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19101
19102
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19103
0
        if (g.IO.ConfigDebugIniSettings)
19104
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19105
0
            {
19106
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19107
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19108
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19109
                // Iterate settings so we can give info about windows that didn't exist during the session.
19110
0
                int contains_window = 0;
19111
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19112
0
                    if (settings->DockId == node_settings->ID)
19113
0
                    {
19114
0
                        if (contains_window++ == 0)
19115
0
                            buf->appendf(" ; contains ");
19116
0
                        buf->appendf("'%s' ", settings->GetName());
19117
0
                    }
19118
0
            }
19119
19120
0
        buf->appendf("\n");
19121
0
    }
19122
0
    buf->appendf("\n");
19123
0
}
19124
19125
19126
//-----------------------------------------------------------------------------
19127
// [SECTION] PLATFORM DEPENDENT HELPERS
19128
//-----------------------------------------------------------------------------
19129
19130
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19131
19132
#ifdef _MSC_VER
19133
#pragma comment(lib, "user32")
19134
#pragma comment(lib, "kernel32")
19135
#endif
19136
19137
// Win32 clipboard implementation
19138
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19139
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19140
{
19141
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19142
    g.ClipboardHandlerData.clear();
19143
    if (!::OpenClipboard(NULL))
19144
        return NULL;
19145
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19146
    if (wbuf_handle == NULL)
19147
    {
19148
        ::CloseClipboard();
19149
        return NULL;
19150
    }
19151
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19152
    {
19153
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19154
        g.ClipboardHandlerData.resize(buf_len);
19155
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19156
    }
19157
    ::GlobalUnlock(wbuf_handle);
19158
    ::CloseClipboard();
19159
    return g.ClipboardHandlerData.Data;
19160
}
19161
19162
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19163
{
19164
    if (!::OpenClipboard(NULL))
19165
        return;
19166
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19167
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19168
    if (wbuf_handle == NULL)
19169
    {
19170
        ::CloseClipboard();
19171
        return;
19172
    }
19173
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19174
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19175
    ::GlobalUnlock(wbuf_handle);
19176
    ::EmptyClipboard();
19177
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19178
        ::GlobalFree(wbuf_handle);
19179
    ::CloseClipboard();
19180
}
19181
19182
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19183
19184
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19185
static PasteboardRef main_clipboard = 0;
19186
19187
// OSX clipboard implementation
19188
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19189
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19190
{
19191
    if (!main_clipboard)
19192
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19193
    PasteboardClear(main_clipboard);
19194
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19195
    if (cf_data)
19196
    {
19197
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19198
        CFRelease(cf_data);
19199
    }
19200
}
19201
19202
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19203
{
19204
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19205
    if (!main_clipboard)
19206
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19207
    PasteboardSynchronize(main_clipboard);
19208
19209
    ItemCount item_count = 0;
19210
    PasteboardGetItemCount(main_clipboard, &item_count);
19211
    for (ItemCount i = 0; i < item_count; i++)
19212
    {
19213
        PasteboardItemID item_id = 0;
19214
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19215
        CFArrayRef flavor_type_array = 0;
19216
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19217
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19218
        {
19219
            CFDataRef cf_data;
19220
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19221
            {
19222
                g.ClipboardHandlerData.clear();
19223
                int length = (int)CFDataGetLength(cf_data);
19224
                g.ClipboardHandlerData.resize(length + 1);
19225
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19226
                g.ClipboardHandlerData[length] = 0;
19227
                CFRelease(cf_data);
19228
                return g.ClipboardHandlerData.Data;
19229
            }
19230
        }
19231
    }
19232
    return NULL;
19233
}
19234
19235
#else
19236
19237
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19238
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19239
0
{
19240
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19241
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19242
0
}
19243
19244
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19245
0
{
19246
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19247
0
    g.ClipboardHandlerData.clear();
19248
0
    const char* text_end = text + strlen(text);
19249
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19250
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19251
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19252
0
}
19253
19254
#endif
19255
19256
// Win32 API IME support (for Asian languages, etc.)
19257
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19258
19259
#include <imm.h>
19260
#ifdef _MSC_VER
19261
#pragma comment(lib, "imm32")
19262
#endif
19263
19264
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19265
{
19266
    // Notify OS Input Method Editor of text input position
19267
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19268
    if (hwnd == 0)
19269
        return;
19270
19271
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19272
    if (HIMC himc = ::ImmGetContext(hwnd))
19273
    {
19274
        COMPOSITIONFORM composition_form = {};
19275
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19276
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19277
        composition_form.dwStyle = CFS_FORCE_POSITION;
19278
        ::ImmSetCompositionWindow(himc, &composition_form);
19279
        CANDIDATEFORM candidate_form = {};
19280
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19281
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19282
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19283
        ::ImmSetCandidateWindow(himc, &candidate_form);
19284
        ::ImmReleaseContext(hwnd, himc);
19285
    }
19286
}
19287
19288
#else
19289
19290
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19291
19292
#endif
19293
19294
//-----------------------------------------------------------------------------
19295
// [SECTION] METRICS/DEBUGGER WINDOW
19296
//-----------------------------------------------------------------------------
19297
// - RenderViewportThumbnail() [Internal]
19298
// - RenderViewportsThumbnails() [Internal]
19299
// - DebugTextEncoding()
19300
// - MetricsHelpMarker() [Internal]
19301
// - ShowFontAtlas() [Internal]
19302
// - ShowMetricsWindow()
19303
// - DebugNodeColumns() [Internal]
19304
// - DebugNodeDockNode() [Internal]
19305
// - DebugNodeDrawList() [Internal]
19306
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19307
// - DebugNodeFont() [Internal]
19308
// - DebugNodeFontGlyph() [Internal]
19309
// - DebugNodeStorage() [Internal]
19310
// - DebugNodeTabBar() [Internal]
19311
// - DebugNodeViewport() [Internal]
19312
// - DebugNodeWindow() [Internal]
19313
// - DebugNodeWindowSettings() [Internal]
19314
// - DebugNodeWindowsList() [Internal]
19315
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19316
//-----------------------------------------------------------------------------
19317
19318
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19319
19320
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19321
0
{
19322
0
    ImGuiContext& g = *GImGui;
19323
0
    ImGuiWindow* window = g.CurrentWindow;
19324
19325
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19326
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19327
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19328
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19329
0
    for (ImGuiWindow* thumb_window : g.Windows)
19330
0
    {
19331
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19332
0
            continue;
19333
0
        if (thumb_window->Viewport != viewport)
19334
0
            continue;
19335
19336
0
        ImRect thumb_r = thumb_window->Rect();
19337
0
        ImRect title_r = thumb_window->TitleBarRect();
19338
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19339
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
19340
0
        thumb_r.ClipWithFull(bb);
19341
0
        title_r.ClipWithFull(bb);
19342
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19343
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19344
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19345
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19346
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19347
0
    }
19348
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19349
0
}
19350
19351
static void RenderViewportsThumbnails()
19352
0
{
19353
0
    ImGuiContext& g = *GImGui;
19354
0
    ImGuiWindow* window = g.CurrentWindow;
19355
19356
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
19357
0
    float SCALE = 1.0f / 8.0f;
19358
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19359
0
    for (ImGuiViewportP* viewport : g.Viewports)
19360
0
        bb_full.Add(viewport->GetMainRect());
19361
0
    ImVec2 p = window->DC.CursorPos;
19362
0
    ImVec2 off = p - bb_full.Min * SCALE;
19363
0
    for (ImGuiViewportP* viewport : g.Viewports)
19364
0
    {
19365
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19366
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19367
0
    }
19368
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19369
0
}
19370
19371
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19372
0
{
19373
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19374
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19375
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19376
0
}
19377
19378
// Draw an arbitrary US keyboard layout to visualize translated keys
19379
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19380
0
{
19381
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
19382
0
    const float  key_rounding = 3.0f;
19383
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
19384
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
19385
0
    const float  key_face_rounding = 2.0f;
19386
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
19387
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19388
0
    const float  key_row_offset = 9.0f;
19389
19390
0
    ImVec2 board_min = GetCursorScreenPos();
19391
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19392
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19393
19394
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19395
0
    const KeyLayoutData keys_to_display[] =
19396
0
    {
19397
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19398
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19399
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19400
0
    };
19401
19402
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19403
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19404
0
    Dummy(board_max - board_min);
19405
0
    if (!IsItemVisible())
19406
0
        return;
19407
0
    draw_list->PushClipRect(board_min, board_max, true);
19408
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19409
0
    {
19410
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19411
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19412
0
        ImVec2 key_max = key_min + key_size;
19413
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19414
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19415
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19416
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19417
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19418
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19419
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19420
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19421
0
        if (IsKeyDown(key_data->Key))
19422
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19423
0
    }
19424
0
    draw_list->PopClipRect();
19425
0
}
19426
19427
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19428
void ImGui::DebugTextEncoding(const char* str)
19429
0
{
19430
0
    Text("Text: \"%s\"", str);
19431
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19432
0
        return;
19433
0
    TableSetupColumn("Offset");
19434
0
    TableSetupColumn("UTF-8");
19435
0
    TableSetupColumn("Glyph");
19436
0
    TableSetupColumn("Codepoint");
19437
0
    TableHeadersRow();
19438
0
    for (const char* p = str; *p != 0; )
19439
0
    {
19440
0
        unsigned int c;
19441
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19442
0
        TableNextColumn();
19443
0
        Text("%d", (int)(p - str));
19444
0
        TableNextColumn();
19445
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19446
0
        {
19447
0
            if (byte_index > 0)
19448
0
                SameLine();
19449
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19450
0
        }
19451
0
        TableNextColumn();
19452
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19453
0
            TextUnformatted(p, p + c_utf8_len);
19454
0
        else
19455
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19456
0
        TableNextColumn();
19457
0
        Text("U+%04X", (int)c);
19458
0
        p += c_utf8_len;
19459
0
    }
19460
0
    EndTable();
19461
0
}
19462
19463
static void DebugFlashStyleColorStop()
19464
0
{
19465
0
    ImGuiContext& g = *GImGui;
19466
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
19467
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
19468
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
19469
0
}
19470
19471
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
19472
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
19473
0
{
19474
0
    ImGuiContext& g = *GImGui;
19475
0
    DebugFlashStyleColorStop();
19476
0
    g.DebugFlashStyleColorTime = 0.5f;
19477
0
    g.DebugFlashStyleColorIdx = idx;
19478
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
19479
0
}
19480
19481
void ImGui::UpdateDebugToolFlashStyleColor()
19482
69.6k
{
19483
69.6k
    ImGuiContext& g = *GImGui;
19484
69.6k
    if (g.DebugFlashStyleColorTime <= 0.0f)
19485
69.6k
        return;
19486
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
19487
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
19488
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
19489
0
        DebugFlashStyleColorStop();
19490
0
}
19491
19492
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19493
static void MetricsHelpMarker(const char* desc)
19494
0
{
19495
0
    ImGui::TextDisabled("(?)");
19496
0
    if (ImGui::BeginItemTooltip())
19497
0
    {
19498
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19499
0
        ImGui::TextUnformatted(desc);
19500
0
        ImGui::PopTextWrapPos();
19501
0
        ImGui::EndTooltip();
19502
0
    }
19503
0
}
19504
19505
// [DEBUG] List fonts in a font atlas and display its texture
19506
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19507
0
{
19508
0
    for (ImFont* font : atlas->Fonts)
19509
0
    {
19510
0
        PushID(font);
19511
0
        DebugNodeFont(font);
19512
0
        PopID();
19513
0
    }
19514
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19515
0
    {
19516
0
        ImGuiContext& g = *GImGui;
19517
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19518
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19519
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19520
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19521
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19522
0
        TreePop();
19523
0
    }
19524
0
}
19525
19526
void ImGui::ShowMetricsWindow(bool* p_open)
19527
0
{
19528
0
    ImGuiContext& g = *GImGui;
19529
0
    ImGuiIO& io = g.IO;
19530
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19531
0
    if (cfg->ShowDebugLog)
19532
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19533
0
    if (cfg->ShowIDStackTool)
19534
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19535
19536
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19537
0
    {
19538
0
        End();
19539
0
        return;
19540
0
    }
19541
19542
    // Basic info
19543
0
    Text("Dear ImGui %s", GetVersion());
19544
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19545
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19546
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19547
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19548
19549
0
    Separator();
19550
19551
    // Debugging enums
19552
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19553
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19554
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19555
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19556
0
    if (cfg->ShowWindowsRectsType < 0)
19557
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19558
0
    if (cfg->ShowTablesRectsType < 0)
19559
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19560
19561
0
    struct Funcs
19562
0
    {
19563
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19564
0
        {
19565
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19566
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19567
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19568
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19569
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19570
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19571
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19572
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19573
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19574
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19575
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19576
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19577
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19578
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19579
0
            IM_ASSERT(0);
19580
0
            return ImRect();
19581
0
        }
19582
19583
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19584
0
        {
19585
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19586
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19587
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19588
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19589
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19590
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19591
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19592
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19593
0
            IM_ASSERT(0);
19594
0
            return ImRect();
19595
0
        }
19596
0
    };
19597
19598
    // Tools
19599
0
    if (TreeNode("Tools"))
19600
0
    {
19601
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19602
0
        SameLine();
19603
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19604
0
        if (show_encoding_viewer)
19605
0
        {
19606
0
            static char buf[100] = "";
19607
0
            SetNextItemWidth(-FLT_MIN);
19608
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19609
0
            if (buf[0] != 0)
19610
0
                DebugTextEncoding(buf);
19611
0
            TreePop();
19612
0
        }
19613
19614
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19615
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19616
0
            DebugStartItemPicker();
19617
0
        SameLine();
19618
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19619
19620
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19621
0
        SameLine();
19622
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19623
19624
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19625
0
        SameLine();
19626
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19627
19628
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19629
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19630
0
        SameLine();
19631
0
        SetNextItemWidth(GetFontSize() * 12);
19632
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19633
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19634
0
        {
19635
0
            BulletText("'%s':", g.NavWindow->Name);
19636
0
            Indent();
19637
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19638
0
            {
19639
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19640
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19641
0
            }
19642
0
            Unindent();
19643
0
        }
19644
19645
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19646
0
        SameLine();
19647
0
        SetNextItemWidth(GetFontSize() * 12);
19648
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19649
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19650
0
        {
19651
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19652
0
            {
19653
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19654
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19655
0
                    continue;
19656
19657
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19658
0
                if (IsItemHovered())
19659
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19660
0
                Indent();
19661
0
                char buf[128];
19662
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19663
0
                {
19664
0
                    if (rect_n >= TRT_ColumnsRect)
19665
0
                    {
19666
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19667
0
                            continue;
19668
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19669
0
                        {
19670
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19671
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19672
0
                            Selectable(buf);
19673
0
                            if (IsItemHovered())
19674
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19675
0
                        }
19676
0
                    }
19677
0
                    else
19678
0
                    {
19679
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19680
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19681
0
                        Selectable(buf);
19682
0
                        if (IsItemHovered())
19683
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19684
0
                    }
19685
0
                }
19686
0
                Unindent();
19687
0
            }
19688
0
        }
19689
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
19690
19691
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19692
0
        SameLine();
19693
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19694
19695
0
        TreePop();
19696
0
    }
19697
19698
    // Windows
19699
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19700
0
    {
19701
        //SetNextItemOpen(true, ImGuiCond_Once);
19702
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19703
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19704
0
        if (TreeNode("By submission order (begin stack)"))
19705
0
        {
19706
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19707
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19708
0
            temp_buffer.resize(0);
19709
0
            for (ImGuiWindow* window : g.Windows)
19710
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
19711
0
                    temp_buffer.push_back(window);
19712
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19713
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19714
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19715
0
            TreePop();
19716
0
        }
19717
19718
0
        TreePop();
19719
0
    }
19720
19721
    // DrawLists
19722
0
    int drawlist_count = 0;
19723
0
    for (ImGuiViewportP* viewport : g.Viewports)
19724
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
19725
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19726
0
    {
19727
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19728
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19729
0
        for (ImGuiViewportP* viewport : g.Viewports)
19730
0
        {
19731
0
            bool viewport_has_drawlist = false;
19732
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
19733
0
            {
19734
0
                if (!viewport_has_drawlist)
19735
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19736
0
                viewport_has_drawlist = true;
19737
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
19738
0
            }
19739
0
        }
19740
0
        TreePop();
19741
0
    }
19742
19743
    // Viewports
19744
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19745
0
    {
19746
0
        Indent(GetTreeNodeToLabelSpacing());
19747
0
        RenderViewportsThumbnails();
19748
0
        Unindent(GetTreeNodeToLabelSpacing());
19749
19750
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19751
0
        SameLine();
19752
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19753
0
        if (open)
19754
0
        {
19755
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19756
0
            {
19757
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19758
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19759
0
                    i, mon.DpiScale * 100.0f,
19760
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19761
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19762
0
            }
19763
0
            TreePop();
19764
0
        }
19765
19766
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19767
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19768
0
        {
19769
0
            static ImVector<ImGuiViewportP*> viewports;
19770
0
            viewports.resize(g.Viewports.Size);
19771
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19772
0
            if (viewports.Size > 1)
19773
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19774
0
            for (ImGuiViewportP* viewport : viewports)
19775
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19776
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19777
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19778
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19779
0
            TreePop();
19780
0
        }
19781
0
        for (ImGuiViewportP* viewport : g.Viewports)
19782
0
            DebugNodeViewport(viewport);
19783
0
        TreePop();
19784
0
    }
19785
19786
    // Details for Popups
19787
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19788
0
    {
19789
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
19790
0
        {
19791
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19792
0
            ImGuiWindow* window = popup_data.Window;
19793
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19794
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19795
0
                popup_data.BackupNavWindow ? popup_data.BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19796
0
        }
19797
0
        TreePop();
19798
0
    }
19799
19800
    // Details for TabBars
19801
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19802
0
    {
19803
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19804
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19805
0
            {
19806
0
                PushID(tab_bar);
19807
0
                DebugNodeTabBar(tab_bar, "TabBar");
19808
0
                PopID();
19809
0
            }
19810
0
        TreePop();
19811
0
    }
19812
19813
    // Details for Tables
19814
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19815
0
    {
19816
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19817
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19818
0
                DebugNodeTable(table);
19819
0
        TreePop();
19820
0
    }
19821
19822
    // Details for Fonts
19823
0
    ImFontAtlas* atlas = g.IO.Fonts;
19824
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19825
0
    {
19826
0
        ShowFontAtlas(atlas);
19827
0
        TreePop();
19828
0
    }
19829
19830
    // Details for InputText
19831
0
    if (TreeNode("InputText"))
19832
0
    {
19833
0
        DebugNodeInputTextState(&g.InputTextState);
19834
0
        TreePop();
19835
0
    }
19836
19837
    // Details for TypingSelect
19838
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
19839
0
    {
19840
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
19841
0
        TreePop();
19842
0
    }
19843
19844
    // Details for Docking
19845
0
#ifdef IMGUI_HAS_DOCK
19846
0
    if (TreeNode("Docking"))
19847
0
    {
19848
0
        static bool root_nodes_only = true;
19849
0
        ImGuiDockContext* dc = &g.DockContext;
19850
0
        Checkbox("List root nodes", &root_nodes_only);
19851
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19852
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19853
0
        SameLine();
19854
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19855
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19856
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19857
0
                if (!root_nodes_only || node->IsRootNode())
19858
0
                    DebugNodeDockNode(node, "Node");
19859
0
        TreePop();
19860
0
    }
19861
0
#endif // #ifdef IMGUI_HAS_DOCK
19862
19863
    // Settings
19864
0
    if (TreeNode("Settings"))
19865
0
    {
19866
0
        if (SmallButton("Clear"))
19867
0
            ClearIniSettings();
19868
0
        SameLine();
19869
0
        if (SmallButton("Save to memory"))
19870
0
            SaveIniSettingsToMemory();
19871
0
        SameLine();
19872
0
        if (SmallButton("Save to disk"))
19873
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19874
0
        SameLine();
19875
0
        if (g.IO.IniFilename)
19876
0
            Text("\"%s\"", g.IO.IniFilename);
19877
0
        else
19878
0
            TextUnformatted("<NULL>");
19879
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19880
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19881
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19882
0
        {
19883
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
19884
0
                BulletText("\"%s\"", handler.TypeName);
19885
0
            TreePop();
19886
0
        }
19887
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19888
0
        {
19889
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19890
0
                DebugNodeWindowSettings(settings);
19891
0
            TreePop();
19892
0
        }
19893
19894
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19895
0
        {
19896
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19897
0
                DebugNodeTableSettings(settings);
19898
0
            TreePop();
19899
0
        }
19900
19901
0
#ifdef IMGUI_HAS_DOCK
19902
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19903
0
        {
19904
0
            ImGuiDockContext* dc = &g.DockContext;
19905
0
            Text("In SettingsWindows:");
19906
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19907
0
                if (settings->DockId != 0)
19908
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19909
0
            Text("In SettingsNodes:");
19910
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19911
0
            {
19912
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19913
0
                const char* selected_tab_name = NULL;
19914
0
                if (settings->SelectedTabId)
19915
0
                {
19916
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19917
0
                        selected_tab_name = window->Name;
19918
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19919
0
                        selected_tab_name = window_settings->GetName();
19920
0
                }
19921
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19922
0
            }
19923
0
            TreePop();
19924
0
        }
19925
0
#endif // #ifdef IMGUI_HAS_DOCK
19926
19927
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19928
0
        {
19929
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19930
0
            TreePop();
19931
0
        }
19932
0
        TreePop();
19933
0
    }
19934
19935
    // Settings
19936
0
    if (TreeNode("Memory allocations"))
19937
0
    {
19938
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
19939
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
19940
0
        Text("Recent frames with allocations:");
19941
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
19942
0
        for (int n = buf_size - 1; n >= 0; n--)
19943
0
        {
19944
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
19945
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
19946
0
        }
19947
0
        TreePop();
19948
0
    }
19949
19950
0
    if (TreeNode("Inputs"))
19951
0
    {
19952
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19953
0
        {
19954
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19955
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19956
0
            Indent();
19957
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19958
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19959
#else
19960
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19961
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19962
#endif
19963
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19964
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19965
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19966
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19967
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19968
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19969
0
            Unindent();
19970
0
        }
19971
19972
0
        Text("MOUSE STATE");
19973
0
        {
19974
0
            Indent();
19975
0
            if (IsMousePosValid())
19976
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19977
0
            else
19978
0
                Text("Mouse pos: <INVALID>");
19979
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19980
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19981
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19982
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19983
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19984
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19985
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
19986
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19987
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19988
0
            Unindent();
19989
0
        }
19990
19991
0
        Text("MOUSE WHEELING");
19992
0
        {
19993
0
            Indent();
19994
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19995
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19996
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19997
0
            Unindent();
19998
0
        }
19999
20000
0
        Text("KEY OWNERS");
20001
0
        {
20002
0
            Indent();
20003
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20004
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20005
0
                {
20006
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20007
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
20008
0
                        continue;
20009
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20010
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20011
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20012
0
                }
20013
0
            EndChild();
20014
0
            Unindent();
20015
0
        }
20016
0
        Text("SHORTCUT ROUTING");
20017
0
        {
20018
0
            Indent();
20019
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20020
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20021
0
                {
20022
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20023
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20024
0
                    {
20025
0
                        char key_chord_name[64];
20026
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20027
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
20028
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
20029
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20030
0
                        idx = routing_data->NextEntryIndex;
20031
0
                    }
20032
0
                }
20033
0
            EndChild();
20034
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20035
0
            Unindent();
20036
0
        }
20037
0
        TreePop();
20038
0
    }
20039
20040
0
    if (TreeNode("Internal state"))
20041
0
    {
20042
0
        Text("WINDOWING");
20043
0
        Indent();
20044
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20045
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20046
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20047
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20048
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20049
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20050
0
        Unindent();
20051
20052
0
        Text("ITEMS");
20053
0
        Indent();
20054
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20055
0
        DebugLocateItemOnHover(g.ActiveId);
20056
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20057
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20058
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20059
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20060
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20061
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20062
0
        Unindent();
20063
20064
0
        Text("NAV,FOCUS");
20065
0
        Indent();
20066
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20067
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20068
0
        DebugLocateItemOnHover(g.NavId);
20069
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20070
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20071
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20072
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20073
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20074
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20075
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20076
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20077
0
        Unindent();
20078
20079
0
        TreePop();
20080
0
    }
20081
20082
    // Overlay: Display windows Rectangles and Begin Order
20083
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20084
0
    {
20085
0
        for (ImGuiWindow* window : g.Windows)
20086
0
        {
20087
0
            if (!window->WasActive)
20088
0
                continue;
20089
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20090
0
            if (cfg->ShowWindowsRects)
20091
0
            {
20092
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20093
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20094
0
            }
20095
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20096
0
            {
20097
0
                char buf[32];
20098
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20099
0
                float font_size = GetFontSize();
20100
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20101
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20102
0
            }
20103
0
        }
20104
0
    }
20105
20106
    // Overlay: Display Tables Rectangles
20107
0
    if (cfg->ShowTablesRects)
20108
0
    {
20109
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20110
0
        {
20111
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20112
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20113
0
                continue;
20114
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20115
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20116
0
            {
20117
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20118
0
                {
20119
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20120
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20121
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20122
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20123
0
                }
20124
0
            }
20125
0
            else
20126
0
            {
20127
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20128
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20129
0
            }
20130
0
        }
20131
0
    }
20132
20133
0
#ifdef IMGUI_HAS_DOCK
20134
    // Overlay: Display Docking info
20135
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20136
0
    {
20137
0
        char buf[64] = "";
20138
0
        char* p = buf;
20139
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20140
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20141
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20142
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20143
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20144
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20145
0
        int depth = DockNodeGetDepth(node);
20146
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20147
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20148
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20149
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20150
0
    }
20151
0
#endif // #ifdef IMGUI_HAS_DOCK
20152
20153
0
    End();
20154
0
}
20155
20156
// [DEBUG] Display contents of Columns
20157
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20158
0
{
20159
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20160
0
        return;
20161
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20162
0
    for (ImGuiOldColumnData& column : columns->Columns)
20163
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20164
0
    TreePop();
20165
0
}
20166
20167
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20168
0
{
20169
0
    using namespace ImGui;
20170
0
    PushID(label);
20171
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20172
0
    Text("%s:", label);
20173
0
    if (!enabled)
20174
0
        BeginDisabled();
20175
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20176
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20177
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20178
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20179
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20180
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20181
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20182
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20183
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20184
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20185
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20186
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20187
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20188
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20189
0
    if (!enabled)
20190
0
        EndDisabled();
20191
0
    PopStyleVar();
20192
0
    PopID();
20193
0
}
20194
20195
// [DEBUG] Display contents of ImDockNode
20196
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20197
0
{
20198
0
    ImGuiContext& g = *GImGui;
20199
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20200
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
20201
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20202
0
    bool open;
20203
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20204
0
    if (node->Windows.Size > 0)
20205
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20206
0
    else
20207
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20208
0
    if (!is_alive) { PopStyleColor(); }
20209
0
    if (is_active && IsItemHovered())
20210
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20211
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20212
0
    if (open)
20213
0
    {
20214
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20215
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20216
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20217
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20218
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20219
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20220
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20221
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20222
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20223
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20224
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20225
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20226
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20227
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20228
0
        {
20229
0
            if (BeginTable("flags", 4))
20230
0
            {
20231
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20232
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20233
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20234
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20235
0
                EndTable();
20236
0
            }
20237
0
            TreePop();
20238
0
        }
20239
0
        if (node->ParentNode)
20240
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20241
0
        if (node->ChildNodes[0])
20242
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20243
0
        if (node->ChildNodes[1])
20244
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20245
0
        if (node->TabBar)
20246
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20247
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20248
20249
0
        TreePop();
20250
0
    }
20251
0
}
20252
20253
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
20254
0
{
20255
0
    if (sizeof(tex_id) >= sizeof(void*))
20256
0
        ImFormatString(buf, buf_size, "0x%p", (void*)*(intptr_t*)(void*)&tex_id);
20257
0
    else
20258
0
        ImFormatString(buf, buf_size, "0x%04X", *(int*)(void*)&tex_id);
20259
0
}
20260
20261
// [DEBUG] Display contents of ImDrawList
20262
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20263
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20264
0
{
20265
0
    ImGuiContext& g = *GImGui;
20266
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20267
0
    int cmd_count = draw_list->CmdBuffer.Size;
20268
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20269
0
        cmd_count--;
20270
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20271
0
    if (draw_list == GetWindowDrawList())
20272
0
    {
20273
0
        SameLine();
20274
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20275
0
        if (node_open)
20276
0
            TreePop();
20277
0
        return;
20278
0
    }
20279
20280
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20281
0
    if (window && IsItemHovered() && fg_draw_list)
20282
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20283
0
    if (!node_open)
20284
0
        return;
20285
20286
0
    if (window && !window->WasActive)
20287
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20288
20289
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20290
0
    {
20291
0
        if (pcmd->UserCallback)
20292
0
        {
20293
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20294
0
            continue;
20295
0
        }
20296
20297
0
        char texid_desc[20];
20298
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
20299
0
        char buf[300];
20300
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20301
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20302
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20303
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20304
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20305
0
        if (!pcmd_node_open)
20306
0
            continue;
20307
20308
        // Calculate approximate coverage area (touched pixel count)
20309
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20310
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20311
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20312
0
        float total_area = 0.0f;
20313
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20314
0
        {
20315
0
            ImVec2 triangle[3];
20316
0
            for (int n = 0; n < 3; n++, idx_n++)
20317
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20318
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20319
0
        }
20320
20321
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20322
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20323
0
        Selectable(buf);
20324
0
        if (IsItemHovered() && fg_draw_list)
20325
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20326
20327
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20328
0
        ImGuiListClipper clipper;
20329
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20330
0
        while (clipper.Step())
20331
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20332
0
            {
20333
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20334
0
                ImVec2 triangle[3];
20335
0
                for (int n = 0; n < 3; n++, idx_i++)
20336
0
                {
20337
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20338
0
                    triangle[n] = v.pos;
20339
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20340
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20341
0
                }
20342
20343
0
                Selectable(buf, false);
20344
0
                if (fg_draw_list && IsItemHovered())
20345
0
                {
20346
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20347
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20348
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20349
0
                    fg_draw_list->Flags = backup_flags;
20350
0
                }
20351
0
            }
20352
0
        TreePop();
20353
0
    }
20354
0
    TreePop();
20355
0
}
20356
20357
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20358
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20359
0
{
20360
0
    IM_ASSERT(show_mesh || show_aabb);
20361
20362
    // Draw wire-frame version of all triangles
20363
0
    ImRect clip_rect = draw_cmd->ClipRect;
20364
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20365
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20366
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20367
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20368
0
    {
20369
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20370
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20371
20372
0
        ImVec2 triangle[3];
20373
0
        for (int n = 0; n < 3; n++, idx_n++)
20374
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20375
0
        if (show_mesh)
20376
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20377
0
    }
20378
    // Draw bounding boxes
20379
0
    if (show_aabb)
20380
0
    {
20381
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20382
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20383
0
    }
20384
0
    out_draw_list->Flags = backup_flags;
20385
0
}
20386
20387
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20388
void ImGui::DebugNodeFont(ImFont* font)
20389
0
{
20390
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20391
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20392
0
    SameLine();
20393
0
    if (SmallButton("Set as default"))
20394
0
        GetIO().FontDefault = font;
20395
0
    if (!opened)
20396
0
        return;
20397
20398
    // Display preview text
20399
0
    PushFont(font);
20400
0
    Text("The quick brown fox jumps over the lazy dog");
20401
0
    PopFont();
20402
20403
    // Display details
20404
0
    SetNextItemWidth(GetFontSize() * 8);
20405
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20406
0
    SameLine(); MetricsHelpMarker(
20407
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
20408
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20409
0
        "You may oversample them to get some flexibility with scaling. "
20410
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20411
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20412
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20413
0
    char c_str[5];
20414
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20415
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20416
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20417
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20418
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20419
0
        if (font->ConfigData)
20420
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20421
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20422
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20423
20424
    // Display all glyphs of the fonts in separate pages of 256 characters
20425
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20426
0
    {
20427
0
        ImDrawList* draw_list = GetWindowDrawList();
20428
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20429
0
        const float cell_size = font->FontSize * 1;
20430
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20431
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20432
0
        {
20433
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20434
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20435
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20436
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20437
0
            {
20438
0
                base += 4096 - 256;
20439
0
                continue;
20440
0
            }
20441
20442
0
            int count = 0;
20443
0
            for (unsigned int n = 0; n < 256; n++)
20444
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20445
0
                    count++;
20446
0
            if (count <= 0)
20447
0
                continue;
20448
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20449
0
                continue;
20450
20451
            // Draw a 16x16 grid of glyphs
20452
0
            ImVec2 base_pos = GetCursorScreenPos();
20453
0
            for (unsigned int n = 0; n < 256; n++)
20454
0
            {
20455
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20456
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20457
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20458
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20459
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20460
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20461
0
                if (!glyph)
20462
0
                    continue;
20463
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20464
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20465
0
                {
20466
0
                    DebugNodeFontGlyph(font, glyph);
20467
0
                    EndTooltip();
20468
0
                }
20469
0
            }
20470
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20471
0
            TreePop();
20472
0
        }
20473
0
        TreePop();
20474
0
    }
20475
0
    TreePop();
20476
0
}
20477
20478
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20479
0
{
20480
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20481
0
    Separator();
20482
0
    Text("Visible: %d", glyph->Visible);
20483
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20484
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20485
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20486
0
}
20487
20488
// [DEBUG] Display contents of ImGuiStorage
20489
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20490
0
{
20491
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20492
0
        return;
20493
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20494
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20495
0
    TreePop();
20496
0
}
20497
20498
// [DEBUG] Display contents of ImGuiTabBar
20499
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20500
0
{
20501
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20502
0
    char buf[256];
20503
0
    char* p = buf;
20504
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20505
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20506
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20507
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20508
0
    {
20509
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20510
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20511
0
    }
20512
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20513
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20514
0
    bool open = TreeNode(label, "%s", buf);
20515
0
    if (!is_active) { PopStyleColor(); }
20516
0
    if (is_active && IsItemHovered())
20517
0
    {
20518
0
        ImDrawList* draw_list = GetForegroundDrawList();
20519
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20520
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20521
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20522
0
    }
20523
0
    if (open)
20524
0
    {
20525
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20526
0
        {
20527
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20528
0
            PushID(tab);
20529
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20530
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20531
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20532
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20533
0
            PopID();
20534
0
        }
20535
0
        TreePop();
20536
0
    }
20537
0
}
20538
20539
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20540
0
{
20541
0
    SetNextItemOpen(true, ImGuiCond_Once);
20542
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20543
0
    {
20544
0
        ImGuiWindowFlags flags = viewport->Flags;
20545
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20546
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20547
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20548
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20549
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20550
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20551
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20552
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20553
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20554
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20555
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20556
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20557
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20558
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20559
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20560
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20561
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20562
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20563
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20564
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20565
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20566
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20567
0
        TreePop();
20568
0
    }
20569
0
}
20570
20571
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20572
0
{
20573
0
    if (window == NULL)
20574
0
    {
20575
0
        BulletText("%s: NULL", label);
20576
0
        return;
20577
0
    }
20578
20579
0
    ImGuiContext& g = *GImGui;
20580
0
    const bool is_active = window->WasActive;
20581
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20582
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20583
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20584
0
    if (!is_active) { PopStyleColor(); }
20585
0
    if (IsItemHovered() && is_active)
20586
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20587
0
    if (!open)
20588
0
        return;
20589
20590
0
    if (window->MemoryCompacted)
20591
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20592
20593
0
    ImGuiWindowFlags flags = window->Flags;
20594
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20595
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20596
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20597
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20598
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20599
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20600
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20601
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20602
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20603
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20604
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20605
0
    {
20606
0
        ImRect r = window->NavRectRel[layer];
20607
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20608
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20609
0
        else
20610
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20611
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20612
0
    }
20613
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20614
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20615
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20616
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20617
20618
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20619
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20620
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20621
0
    if (window->DockNode || window->DockNodeAsHost)
20622
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20623
20624
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20625
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20626
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20627
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20628
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20629
0
    {
20630
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
20631
0
            DebugNodeColumns(&columns);
20632
0
        TreePop();
20633
0
    }
20634
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20635
0
    TreePop();
20636
0
}
20637
20638
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20639
0
{
20640
0
    if (settings->WantDelete)
20641
0
        BeginDisabled();
20642
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20643
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20644
0
    if (settings->WantDelete)
20645
0
        EndDisabled();
20646
0
}
20647
20648
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20649
0
{
20650
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20651
0
        return;
20652
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20653
0
    {
20654
0
        PushID((*windows)[i]);
20655
0
        DebugNodeWindow((*windows)[i], "Window");
20656
0
        PopID();
20657
0
    }
20658
0
    TreePop();
20659
0
}
20660
20661
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20662
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20663
0
{
20664
0
    for (int i = 0; i < windows_size; i++)
20665
0
    {
20666
0
        ImGuiWindow* window = windows[i];
20667
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20668
0
            continue;
20669
0
        char buf[20];
20670
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20671
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20672
0
        DebugNodeWindow(window, buf);
20673
0
        Indent();
20674
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20675
0
        Unindent();
20676
0
    }
20677
0
}
20678
20679
//-----------------------------------------------------------------------------
20680
// [SECTION] DEBUG LOG WINDOW
20681
//-----------------------------------------------------------------------------
20682
20683
void ImGui::DebugLog(const char* fmt, ...)
20684
0
{
20685
0
    va_list args;
20686
0
    va_start(args, fmt);
20687
0
    DebugLogV(fmt, args);
20688
0
    va_end(args);
20689
0
}
20690
20691
void ImGui::DebugLogV(const char* fmt, va_list args)
20692
0
{
20693
0
    ImGuiContext& g = *GImGui;
20694
0
    const int old_size = g.DebugLogBuf.size();
20695
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20696
0
    g.DebugLogBuf.appendfv(fmt, args);
20697
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20698
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20699
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20700
#ifdef IMGUI_ENABLE_TEST_ENGINE
20701
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
20702
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
20703
#endif
20704
0
}
20705
20706
void ImGui::ShowDebugLogWindow(bool* p_open)
20707
0
{
20708
0
    ImGuiContext& g = *GImGui;
20709
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20710
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20711
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20712
0
    {
20713
0
        End();
20714
0
        return;
20715
0
    }
20716
20717
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20718
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20719
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20720
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20721
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20722
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20723
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20724
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20725
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20726
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20727
20728
0
    if (SmallButton("Clear"))
20729
0
    {
20730
0
        g.DebugLogBuf.clear();
20731
0
        g.DebugLogIndex.clear();
20732
0
    }
20733
0
    SameLine();
20734
0
    if (SmallButton("Copy"))
20735
0
        SetClipboardText(g.DebugLogBuf.c_str());
20736
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20737
20738
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
20739
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
20740
20741
0
    ImGuiListClipper clipper;
20742
0
    clipper.Begin(g.DebugLogIndex.size());
20743
0
    while (clipper.Step())
20744
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20745
0
        {
20746
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20747
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20748
0
            TextUnformatted(line_begin, line_end); // Display line
20749
0
            ImRect text_rect = g.LastItemData.Rect;
20750
0
            if (IsItemHovered())
20751
0
                for (const char* p = line_begin; p <= line_end - 10; p++) // Search for 0x???????? identifiers
20752
0
                {
20753
0
                    ImGuiID id = 0;
20754
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20755
0
                        continue;
20756
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20757
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20758
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20759
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20760
0
                        DebugLocateItemOnHover(id);
20761
0
                    p += 10;
20762
0
                }
20763
0
        }
20764
0
    g.DebugLogFlags = backup_log_flags;
20765
0
    if (GetScrollY() >= GetScrollMaxY())
20766
0
        SetScrollHereY(1.0f);
20767
0
    EndChild();
20768
20769
0
    End();
20770
0
}
20771
20772
//-----------------------------------------------------------------------------
20773
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
20774
//-----------------------------------------------------------------------------
20775
20776
// Draw a small cross at current CursorPos in current window's DrawList
20777
void ImGui::DebugDrawCursorPos(ImU32 col)
20778
0
{
20779
0
    ImGuiContext& g = *GImGui;
20780
0
    ImGuiWindow* window = g.CurrentWindow;
20781
0
    ImVec2 pos = window->DC.CursorPos;
20782
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
20783
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
20784
0
}
20785
20786
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
20787
void ImGui::DebugDrawLineExtents(ImU32 col)
20788
0
{
20789
0
    ImGuiContext& g = *GImGui;
20790
0
    ImGuiWindow* window = g.CurrentWindow;
20791
0
    float curr_x = window->DC.CursorPos.x;
20792
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
20793
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
20794
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
20795
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
20796
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
20797
0
}
20798
20799
// Draw last item rect in ForegroundDrawList (so it is always visible)
20800
void ImGui::DebugDrawItemRect(ImU32 col)
20801
0
{
20802
0
    ImGuiContext& g = *GImGui;
20803
0
    ImGuiWindow* window = g.CurrentWindow;
20804
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
20805
0
}
20806
20807
// [DEBUG] Locate item position/rectangle given an ID.
20808
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20809
20810
void ImGui::DebugLocateItem(ImGuiID target_id)
20811
0
{
20812
0
    ImGuiContext& g = *GImGui;
20813
0
    g.DebugLocateId = target_id;
20814
0
    g.DebugLocateFrames = 2;
20815
0
}
20816
20817
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20818
0
{
20819
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20820
0
        return;
20821
0
    ImGuiContext& g = *GImGui;
20822
0
    DebugLocateItem(target_id);
20823
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20824
0
}
20825
20826
void ImGui::DebugLocateItemResolveWithLastItem()
20827
0
{
20828
0
    ImGuiContext& g = *GImGui;
20829
0
    ImGuiLastItemData item_data = g.LastItemData;
20830
0
    g.DebugLocateId = 0;
20831
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20832
0
    ImRect r = item_data.Rect;
20833
0
    r.Expand(3.0f);
20834
0
    ImVec2 p1 = g.IO.MousePos;
20835
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20836
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20837
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20838
0
}
20839
20840
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20841
void ImGui::UpdateDebugToolItemPicker()
20842
69.6k
{
20843
69.6k
    ImGuiContext& g = *GImGui;
20844
69.6k
    g.DebugItemPickerBreakId = 0;
20845
69.6k
    if (!g.DebugItemPickerActive)
20846
69.6k
        return;
20847
20848
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20849
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20850
0
    if (IsKeyPressed(ImGuiKey_Escape))
20851
0
        g.DebugItemPickerActive = false;
20852
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20853
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20854
0
    {
20855
0
        g.DebugItemPickerBreakId = hovered_id;
20856
0
        g.DebugItemPickerActive = false;
20857
0
    }
20858
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20859
0
        if (change_mapping && IsMouseClicked(mouse_button))
20860
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20861
0
    SetNextWindowBgAlpha(0.70f);
20862
0
    if (!BeginTooltip())
20863
0
        return;
20864
0
    Text("HoveredId: 0x%08X", hovered_id);
20865
0
    Text("Press ESC to abort picking.");
20866
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20867
0
    if (change_mapping)
20868
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20869
0
    else
20870
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20871
0
    EndTooltip();
20872
0
}
20873
20874
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
20875
void ImGui::UpdateDebugToolStackQueries()
20876
69.6k
{
20877
69.6k
    ImGuiContext& g = *GImGui;
20878
69.6k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20879
20880
    // Clear hook when id stack tool is not visible
20881
69.6k
    g.DebugHookIdInfo = 0;
20882
69.6k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20883
69.6k
        return;
20884
20885
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20886
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20887
5
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20888
5
    if (tool->QueryId != query_id)
20889
0
    {
20890
0
        tool->QueryId = query_id;
20891
0
        tool->StackLevel = -1;
20892
0
        tool->Results.resize(0);
20893
0
    }
20894
5
    if (query_id == 0)
20895
5
        return;
20896
20897
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20898
0
    int stack_level = tool->StackLevel;
20899
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20900
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20901
0
            tool->StackLevel++;
20902
20903
    // Update hook
20904
0
    stack_level = tool->StackLevel;
20905
0
    if (stack_level == -1)
20906
0
        g.DebugHookIdInfo = query_id;
20907
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20908
0
    {
20909
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20910
0
        tool->Results[stack_level].QueryFrameCount++;
20911
0
    }
20912
0
}
20913
20914
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
20915
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20916
0
{
20917
0
    ImGuiContext& g = *GImGui;
20918
0
    ImGuiWindow* window = g.CurrentWindow;
20919
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20920
20921
    // Step 0: stack query
20922
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20923
0
    if (tool->StackLevel == -1)
20924
0
    {
20925
0
        tool->StackLevel++;
20926
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20927
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20928
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20929
0
        return;
20930
0
    }
20931
20932
    // Step 1+: query for individual level
20933
0
    IM_ASSERT(tool->StackLevel >= 0);
20934
0
    if (tool->StackLevel != window->IDStack.Size)
20935
0
        return;
20936
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20937
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20938
20939
0
    switch (data_type)
20940
0
    {
20941
0
    case ImGuiDataType_S32:
20942
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20943
0
        break;
20944
0
    case ImGuiDataType_String:
20945
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20946
0
        break;
20947
0
    case ImGuiDataType_Pointer:
20948
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20949
0
        break;
20950
0
    case ImGuiDataType_ID:
20951
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20952
0
            return;
20953
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20954
0
        break;
20955
0
    default:
20956
0
        IM_ASSERT(0);
20957
0
    }
20958
0
    info->QuerySuccess = true;
20959
0
    info->DataType = data_type;
20960
0
}
20961
20962
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20963
0
{
20964
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20965
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20966
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20967
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20968
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20969
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20970
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20971
0
        return (*buf = 0);
20972
#ifdef IMGUI_ENABLE_TEST_ENGINE
20973
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20974
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20975
#endif
20976
0
    return ImFormatString(buf, buf_size, "???");
20977
0
}
20978
20979
// ID Stack Tool: Display UI
20980
void ImGui::ShowIDStackToolWindow(bool* p_open)
20981
0
{
20982
0
    ImGuiContext& g = *GImGui;
20983
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20984
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20985
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20986
0
    {
20987
0
        End();
20988
0
        return;
20989
0
    }
20990
20991
    // Display hovered/active status
20992
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20993
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20994
0
    const ImGuiID active_id = g.ActiveId;
20995
#ifdef IMGUI_ENABLE_TEST_ENGINE
20996
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20997
#else
20998
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20999
0
#endif
21000
0
    SameLine();
21001
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21002
21003
    // CTRL+C to copy path
21004
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21005
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21006
0
    SameLine();
21007
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21008
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
21009
0
    {
21010
0
        tool->CopyToClipboardLastTime = (float)g.Time;
21011
0
        char* p = g.TempBuffer.Data;
21012
0
        char* p_end = p + g.TempBuffer.Size;
21013
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21014
0
        {
21015
0
            *p++ = '/';
21016
0
            char level_desc[256];
21017
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21018
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21019
0
            {
21020
0
                if (level_desc[n] == '/')
21021
0
                    *p++ = '\\';
21022
0
                *p++ = level_desc[n];
21023
0
            }
21024
0
        }
21025
0
        *p = '\0';
21026
0
        SetClipboardText(g.TempBuffer.Data);
21027
0
    }
21028
21029
    // Display decorated stack
21030
0
    tool->LastActiveFrame = g.FrameCount;
21031
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21032
0
    {
21033
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
21034
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21035
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21036
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21037
0
        TableHeadersRow();
21038
0
        for (int n = 0; n < tool->Results.Size; n++)
21039
0
        {
21040
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21041
0
            TableNextColumn();
21042
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21043
0
            TableNextColumn();
21044
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21045
0
            TextUnformatted(g.TempBuffer.Data);
21046
0
            TableNextColumn();
21047
0
            Text("0x%08X", info->ID);
21048
0
            if (n == tool->Results.Size - 1)
21049
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21050
0
        }
21051
0
        EndTable();
21052
0
    }
21053
0
    End();
21054
0
}
21055
21056
#else
21057
21058
void ImGui::ShowMetricsWindow(bool*) {}
21059
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21060
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21061
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21062
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21063
void ImGui::DebugNodeFont(ImFont*) {}
21064
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21065
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21066
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21067
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21068
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21069
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21070
21071
void ImGui::DebugLog(const char*, ...) {}
21072
void ImGui::DebugLogV(const char*, va_list) {}
21073
void ImGui::ShowDebugLogWindow(bool*) {}
21074
void ImGui::ShowIDStackToolWindow(bool*) {}
21075
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21076
void ImGui::UpdateDebugToolItemPicker() {}
21077
void ImGui::UpdateDebugToolStackQueries() {}
21078
void ImGui::UpdateDebugToolFlashStyleColor() {}
21079
21080
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21081
21082
//-----------------------------------------------------------------------------
21083
21084
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21085
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21086
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21087
#include "imgui_user.inl"
21088
#endif
21089
21090
//-----------------------------------------------------------------------------
21091
21092
#endif // #ifndef IMGUI_DISABLE